Inheritance

Q: What is inheritance in java?

Q: Different level of inheritance in java?

Q: How to implement inheritance in java?

Q: What is hybrid inheritance?

Q: What is multiple inheritance?

Inheritance is a mechanism by which we can inherits some existing features of another class.

Inheritance consist of 2 or more classes.

One is super class and another is subclass Super class is that class from which we inherits some features. It is also called as parent class or root class. whereas Subclass is that which inherit feature from super class. It is also called as child class Inheritance is a relationship between subclass and super class.

Consider a example of vehicles , a 4 wheeler vehicle, cars, maruti and alto. 4 wheeler vehicle is extended from vehicle then vehicle is super class whereas 4 wheeler vehicle is subclass. Similarly cars is extended from 4 wheeler vehicle, and maruti and alto is extended from cars. Vehicles is super class of all of this whereas , a 4 wheeler vehicle, cars, maruti and alto are subclass. As we all have the same ancestors similarly inheritance works.

We can inherit a class by simply writing following code: class Alto extends cars

TYPE OF INHERITANCE

Single Inheritance: If only one subclass inherit a super class then it is called as superclass.
singleinher_hir

singleinher_output

Upcasting

Q: What is upcasting in inheritance?
Q: What is upcasting in java?
Q: How to implement upcasting in java?
Q: What is upcasting?

Upcasting means an object of subclass type can be treated as super class type. Casting here doesn’t mean changing one primitive to another.
EXAMPLE
Consider this hierarchy.
VEHICLE
4 WHEELER
CARS
ALTO MARUTI

SYNTAX
alto a=new alto();
System.out.println(a);
vehicle v=a; //upcasting
System.out.println(v);

Upcasting is done automatically.

Different SYNTAX for upcasting are:-

  • vehicle v = (vehicle) new alto();
  • vehicle v = new alto();
  • Alto is also car and 4 wheeler vehicle, which logically means – if car has staring and 4 wheeler vehicle has seats, then alto has a staring and seats too.

    What this means for a programmer, is that we don’t need to write for every possible 4 wheeler vehicle that it has staring or seats. We just need to write it once, and every car gets it through inheritance.
    Alto is still alto but compiler treat it as a vehicle

    upcasting_hir

    upcasting_output