Java Inheritance Example
Java Inheritance Example
As displayed in the above figure, Programmer is the subclass and Employee is the
superclass.
The relationship between the two classes is Programmer IS-A Employee. It means
that Programmer is a type of Employee.
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Output :
Programmer salary is: 40000.0
Bonus of programmer is: 10000
In the above example, Programmer object can access the field of own class as well
as of Employee class i.e. code reusability.
Here is the sample code for a possible implementation of a Bicycle class that was
presented in the Classes and Objects lesson:
public class Bicycle {
seatHeight = startHeight;
}
// filename: Main.java
class Base {
Base() {
}
Derived() {
}
}
}
But, if we want to call parameterized contructor of base class, then we can call it
using super(). The point to note is base class constructor call must be the first
line in derived class constructor. For example, in the following program,
super(_x) is first line derived class constructor.
// filename: Main.java
class Base {
int x;
Base(int _x) {
x = _x;
}
class Derived extends Base {
int y;
super(_x);
y = _y;
}
void Display() {
}
d.Display();
}
Output:
x = 10, y = 20
Terms used in 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. The meaning of "extends" is to increase the functionality.