Monday, July 4, 2011

private and final method overriding

I am going to explain the following case .

Case1:what happen when we override private method ?
Case2:what happen when we override final method ?
Case3:what happen when we override private with final method ?

Case1:what happen when we override private method ?
Explain :
Source code of Parent class
public class Parent {
public Parent() {
super();
}
private void hello(){
System.out.println("parent class");
}
}


Source code of Child class
public class Child extends Parent{
    public Child() {
        super();
    }
    private void hello(){
      System.out.println("child class method ");
    }}
Child class has same method but this is not called method overriding because the method is make private in Parent class .this is just a new method declaration .
SO do not confuse .compiler  does not complain you it run fine without any exception .

Case2:what happen when we override final method ?
Parent Class Code :
public class Parent {
    public Parent() {
        super();
    }
     public final void hello(){
      System.out.println("parent class");
    }
}
Child class Code :
  public class Child extends Parent{
    public Child() {
        super();
    }
    public  void hello(){
      System.out.println("child class method ");
    }
   }
If you going to run this it give you following compile time exception
Exception: hello() in model.Child cannot override hello() in model.Parent; overridden method is final
this time compiler know you are going to override final method which is not possible .so compiler  do not allow you  to redefine same method in child .
This is main difference between  private method and final method overriding.

Case3:what happen when we override private with final method ?
Parent Class :
public class Parent {
    public Parent() {
        super();
    }
     private final void hello(){
      System.out.println("Parent Class");
    }
}
Child Class :
public class Child extends Parent{
    public Child() {
        super();
    }
  private final void hello(){
    System.out.println("Child Class ");
  }
}
Here private is win over final .it means it's not going to give any compile  time exception .because we make Parent method as private which not inherit in Child method .if you define the method this way it meas you just redefine method again .Case 1 rule is applicable .