Java Inheritance

Inheritance is a mechanism in which one class acquires all the methods and fields of another class for code re-usability. The child class which acquires the properties is called sub class or derived class and the class whose properties are acquired is called super class or base class. The “extends” keyword is used to inherit the properties of a super class in a sub class.

Java Inheritance Systax

class JavaParentClass {

//body of base class (method, fields etc)

}

class JavaSubClass extends JavaParentClass {

//methods and fields from JavaParentClass are inherited.

//body of subclass (method, fields etc)

}

Inheritance Example

class JavaParentClass {

int x = 50;

public void welcomeParent(){

System.out.println(“I am in parent class”);

}

}

class JavaInheritance extends JavaParentClass {

int y = 20;

public void welcomeChild(){

System.out.println(“I am in child class”);

}

public static void main(String args[])
{

JavaInheritance c = new JavaInheritance();
c.welcomeParent();
System.out.println(“Value of x is ” + c.x);
c.welcomeChild();
System.out.println(“Value of y is ” + c.y);

}

}

Output

I am in parent class
Value of x is 50
I am in child class
Value of y is 20

super keyword

It is same as this keyword but it is used to access/invoke the members of super class. It differentiate parent class and child class methods with same names. Also it can be used in sub class to invoke the constructor of parent class.

Example

class JavaParentClass{

public void welcome(){

System.out.println(“I am in super class”);

}

}

public class JavaSuperExample extends JavaParentClass {

public void welcome(){

System.out.println(“I am in child class”);

}

public void display(){

JavaSuperExample obj = new JavaSuperExample();
obj.welcome();

//invoking super class method
super.welcome();

}

public static void main(String args[]){

JavaSuperExample obj = new JavaSuperExample();

obj.display();

}

}

Output

I am in child class
I am in super class

Leave a Reply

Your email address will not be published. Required fields are marked *