Inheritance :
Creating a class from an existing class is called inheritance.
The existing class is called the Super Class / Parent class / Base class.
The derived class is called the Subclass / Child class / Derived class.
We can achieve inheritance with the help of
extendskeywords.Inheritance related to reusability of the code .
1: Single Inheritance
- Creating a class with the help of single super class is called Single Inheritance .
- Here only one sub class and only one super class .
//Single Inheritance
class Vehicle
{
}
class Car extends Vehicle
{
void main(){}
}
2: Multilevel Inheritance
- Creating a class with the help of Sub-class is known as Multilevel Inheritance .
- Here more then One level present .
//Multilevel Inheritance
class ElectronicDevice
{
}
class MobileDevice extends ElectronicDevice
{
}
class SmartPhone extends MobileDevice
{
void main(){}
}
3: Multiple Inheritance
- creating a class with the help of more than one super class is called Multiple Inheritance .
- java class does not support multiple inheritance (b/c ambiguity to call ).
- But we achieve multiple inheritance with the help of interface .
//Multiple Inheritance
class A
{
}
class B
{
}
class Car extends A ,B
{
void main(){}
}
error: '{' expected
class Car extends A ,B
^
1 error
4: Hierarchical Inheritance
- creating more than one sub classes with the help of single super class is known as Hierarchical Inheritance .
- here one super class but more than one sub class .
//Hierarchical inheritance
class Vehicle
{
}
class Car extends Vehicle
{
}
class Bike extends Vehicle
{
void main(){
IO.println("hi java");
}
}
5: Hybrid Inheritance
-It is a combination of more than one type of inheritance.
// Hybrid inheritance
class A
{
}
class B extends A
{
}
class D extends A
{
}
class C extends B
{
void main(){}
}
Why does Java not support multiple inheritance?
Why can’t a child class reference variable hold a parent class object?
// Why can’t a child class reference variable hold a parent class object?
class Vehicle{
int x=10;
int y=20;
}
class Car extends Vehicle {
int a=100;
int b=200;
public static void main(String[] args) {
Vehicle v1 = new Vehicle();
Car c1 = new Car();
Vehicle v2 = new Car();
}
}
Notes
Car c2 = new Vehicle();
error: incompatible types: Vehicle cannot be converted to Car
Car c2 = new Vehicle();
note
Here , Car class reference variable ( c2 ) requirement a , b , x and y non- static variables but vehicle object having only x and y . that's why it is Invalid . Hence , child class reference variable can not hold Parent / Super class Object .
But Super class reference variable ( v2 ) can hold sub - class Object .
here , Car class is sub class and car object having x, y ,a, and b non- static variable but Vehicle class reference variable requirement only x and y . (no problem because car object fulfill the requirement of Vehicle class reference variable . )








Top comments (0)