It2EDU

Sunday, December 25, 2016

Inheritance in Java


Inheritance:








Inheritance
is an ability to derive new classes from existing classes. A derived class is
known as subclass which inherits the instance variables and methods of the
super class or base class, and can add some new instance variables and methods.You are not limited to
just one layer of inheritance. The inheritance tree, or class hierarchy can be as deep
as needed. Methods and variables are inherited down through the levels. In general,
the farther down in the hierarchy a class appears, the more
specialized its behavior.





Inheritance defines is-a relationship between a Super class and its Sub class.





Inheritance may have
different forms.











Types
of Inheritance:





Single
Inheritance:
In this type a sub class can have only one super class.







Single Inheritance


Single Inheritance













Multiple
Inheritance
: In this type of inheritance can have several super classes for a sub
class.










Multiple inheritance
Multiple Inheritance  














Multilevel
Inheritance
: This type is derived from another sub class.







multilevel inheritance
Multilevel Inheritance











Hierarchical Inheritance:  This form has one super class and many sub
classes.







hierarchical inheritance
Hierarchical Inheritance






 Java Does not support Multiple Inheritance why? Because java is simple, easy in case if java supports multiple inheritance it leads to complexity so to avoid that java does not support multiple inheritance.















 Demonstrate Inheritance in Java:








class Vehicle
{
    String typeOfVehicle;
}
public class Car extends Vehicle {
   
    String modelType;
    public void showDetail()
    {
       
typeOfVehicle= "Car";        //accessing Vehicle class member
        modelType = "sports";
        System.out.println(modelType+" "+
typeOfVehicle);
    }
    public static void main(String[] args)
    {
        Car car =new Car();
        car.showDetail();
    }
}





Output of the above program:





Sports car

































0 comments:

Post a Comment