Lecture 8
Lecture 8
Unit 1
Lecture 8
Lecture 8
• Inheritance
• Super Class
• Sub Class
• Access Specifies
Inheritance in Java
• Inheritance is an important pillar of
OOP(Object-Oriented Programming).
• It is the mechanism in Java by which one class is
allowed to inherit the features(fields and
methods) of another class.
• In Java, Inheritance means creating new classes
based on existing ones.
• A class that inherits from another class can
reuse the methods and fields of that class.
• In addition, you can add new fields and
methods to your current class as well.
Why use inheritance in java
• For Method Overriding (so runtime
polymorphism can be achieved).
• For Code Reusability.
Syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
The extends keyword indicates that you are
making a new class that derives from an
existing class.
Super Class/Parent Class:
The class whose features are inherited
is known as a superclass(or a base
class or a parent class).
Sub Class/Child Class:
The class that inherits the other class
is known as a subclass(or a derived
class, extended class, or child class).
The subclass can add its own fields
and methods in addition to the
superclass fields and methods.
import java.io.*;
// Base or Super Class
class Employee {
int salary = 60000;
}
// Inherited or Sub Class
class Engineer extends Employee {
int benefits = 10000;
}
class MyMain {
public static void main(String args[])
{
Engineer E1 = new Engineer();
System.out.println("Salary : " + E1.salary
+ "Benefits : " + E1.benefits);
}
}
Salary : 60000
Benefits : 10000
Types of inheritance in java
Why multiple inheritance is not supported in java?
• To reduce the complexity and simplify the
language, multiple inheritance is not
supported in java.
• Consider a scenario where A, B and C are three
classes. The C class inherits A and B classes. If
A and B classes have same method and you
call it from child class object, there will be
ambiguity to call method of A or B class.
• Since compile time errors are better than
runtime errors.
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
} Output:Hello
public access modifier
• The public access modifier is accessible
everywhere. It has the widest scope among all
other modifiers.
Non Access Modifiers:
Java provides a number of non-access modifiers
to achieve many other functionality.
• The static modifier for creating class methods
and variables
• The final modifier for finalizing the
implementations of classes, methods, and
variables.
• The abstract modifier for creating abstract
classes and methods.