Saturday, October 19, 2013

Inheritance prevention mechanism in java..

Inheritance prevention mechanism :

As of my knowledge, I got two mechanisms to prevent inheritance in java.

1) Using final keyword
2) Using private keyword


1) We know the usage of final keyword.

- If we use 'final' for any variable, that variable can't be changed later.
- If we use 'final' for any instance method, that method can't be overridden.
- If we use 'final' for any class, that class can't be inherited or extended.

example code:
public final class A{

}//end class

public class B extends A{ // can't be done

}//end class

- we will get compilation error stating that the class A is final and can't extend.



2) We know that we can't write private in front of the class.

But we can write this private keyword in front of the constructor. ( used in singleton class)
- It means, once we specify the constructor as private, no one can call that constructor from outside of that class.
- So by using this logic, we can say that we can't extend that class.

explanation: 

- If we see constructor chaining, the child class constructor should call its parent class constructor then only the object creation will be done. If the child class is unable to call its parent class constructor then we can't use that class to create an object.
- From the above logic, once the constructor is declared as private then No other class can extend this class.



example code:

public class A{
      //private constructor
      private A(){
      }
}//end class

public class B extends A{
   //public constructor
   public B(){
    }
}//end class


If we try to compile class B, we will get compilation  error that ....

A() has private access in A
public class B extends A{
       ^
1 error

No comments:

Post a Comment