Java - Inheritance

1InheritanceInheritance is a process where one object acquires the properties of another object
2SubclassClass which inherits the properties of another object is called as subclass
3SuperclassClass whose properties are inherited by subclass is called as superclass
4Keywords Usedextends and implements
Extends Keyword : We can extend a class by using the extends keyword in a class declaration after the class name and before the parent class.

public class ParentClass {


and we define child class like shown below.

public class ChildClass extends ParentClass {


Inheritance can be achieved only using the IS-A relationship.
IS-A Relationship :
saying, This object is a type of that object.

public class Vehicle{

public class FourWheeler extends Vehicle{

public class TwoWheeler extends Vehicle{

public class WagonR extends FourWheeler{

From the above example we can say that :
  1. Vehicle is the superclass of TwoWheeler and FourWheeler class.
  2. TwoWheeler and FourWheeler are sub classes of Vehicle class.
  3. WagonR is the subclass of both FourWheeler and Vehicle classes.
IS-A relationship :
TwoWheeler IS-A Vehicle
FourWheeler IS-A Vehicle

IS-A Relationship Verification: using instanceof

class FourWheeler extends Vehicle{}
class TwoWheeler extends Vehicle{}
class WagonR extends FourWheeler{}

public class Vehicle 
    public static void main( String[] args )
    	FourWheeler v1 = new FourWheeler();
    	TwoWheeler v2 = new TwoWheeler();
    	WagonR v3 = new WagonR();
        System.out.println(v1 instanceof Vehicle);
        System.out.println(v2 instanceof Vehicle);
        System.out.println(v3 instanceof Vehicle);
        System.out.println(v3 instanceof FourWheeler);

WagonR IS-A FourWheeler

WagonR IS-A Vehicle

Access Specifier :
  1. From subclass we cannot access the private members of the superclass.
  2. Subclass you can access its superclass's public and protected methods and fields.

Java method overriding :
  1. Same Argument List.
  2. The return type.
  3. Modification of access level.
  4. Cannot Override Final Methods.
  5. Cannot Override Static Methods.
Super Keyword : Super is used to refer the immediate parent of the class. Whenever we create an object of the child class then the reference to the parent class will be created automatically.

We can user super keyword by using three ways :
  1. Accessing Instance Variable of Parent Class
  2. Accessing Parent Class Method
  3. Accessing Parent Class Class Constructor
Final Keyword : | Raju