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


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



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.
Consider this hierarchy.

alto a=new alto();
vehicle v=a; //upcasting

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