Friday, March 10, 2017

Inheritance in Java

The process of obtaining the data members and methods from one class to another class is known as inheritance. It is one of the fundamental features of object-oriented programming.
The idea behind inheritance in java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of parent class, and you can add new methods and fields also.
Inheritance represents the IS-A relationship, also known as parent-child relationship.
Let us see how extend keyword is used to achieve Inheritance.

class Vehicle
{
  …… 
}
class Car extends Vehicle
{
 …….   //extends the property of vehicle class.
}
Now based on above example. In OOPs term we can say that,
• Vehicle is super class of Car.
• Car is sub class of Vehicle.
• Car IS-A Vehicle.

Why use Inheritance?

• For Method Overriding (used for Runtime Polymorphism).
• It’s main uses are to enable polymorphism and to be able to reuse code for different      classes by putting it in a common super class
• For code Re-usability

Simple example of Inheritance

class Parent
{
   public void p1()
   {
        System.out.println(“Parent method”);
   }
}
public class Child extends Parent 
{
  public void c1()
   {
        System.out.println(“Child method”);
   }
public static void main(String[] args)
  {
       Child cobj = new Child();
       cobj.c1(); //method of Child class
       cobj.p1(); //method of Parent class 
  }
}
Output :
Child method
Parent method

Types of Inheritance

1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
NOTE*: Multiple inheritance is not supported in java.Inheritance Content -1

Q. Why multiple inheritance is not supported in Java

• To remove ambiguity.
• To provide more maintainable and clear design.
Inheritance Content -2

Q. What is not possible using java class Inheritance?

1. Private members of the superclass are not inherited by the subclass and can only be indirectly accessed.
2. Members that have default accessibility in the superclass are also not inherited by subclasses in other packages, as these members are only accessible by their simple names in subclasses within the same package as the superclass.
3. Since constructors and initializer blocks are not members of a class, they are not inherited by a subclass.
4. A subclass can extend only one superclass

No comments:

Post a Comment