What is Inheritance in Java with example

What is Inheritance in Java with example

One class in Java can get the methods and properties from other class – this helps reducing the coding efforts , increase code reusability and maintainability.

e.g. 

public class classB extends classB {

}

in the above Java code, classB class gets the methods and properties from classA class.

steps,

  1. create a meaningful project and a package in eclipse
  2. create 2 classes classA and classB under the package (Codes are below)

Code for classA class as below:

package inheritancePkg;

public class classA {

public void A()

{

System.out.println(“this is from father class”);
}

}

 

Code for classB class as below:

package inheritancePkg;

public class classB extends classA // extends classA is inheritance from classA class to classB

// so we are able to write obj1.add() from father.

{
public static void main(String[] args)
{

classB obj1 = new classB();
obj1.A();
obj1.B();

}

public void B()

{
System.out.println(“this is from son class “);

}

}