Tuesday, December 11, 2018

Java OOPS: Inheritance (Overriding) Part 5 Various Rules

Hi All,

We have seen various cases/ rules of overriding in my previous posts . Now in this post I am listing some more rule on the basis of different type of methods for ex: final, synchronized , native etc. I am showing the rough syntax to show just rules. You can check by implementing these rules in your code . ;)

Case I :  

Parent{
      final m1(){} 

}
Child extends Parent {
      final/non-final m1(){}
}


Valid Or Not :
Not Valid



Case II :  

Parent{
       non-final m1(){}
}
Child extends Parent {
       final m1(){}
}

Valid Or Not :
Valid

Case III :  

Parent{
     abstract m1(){}
}
Child extends Parent {
     non-abstract m1(){}
}

Valid Or Not :

Valid



Case IV :

 Parent{
       non-abstract m1(){}
 }
Child extends Parent {
       non-abstract m1(){}
}


Valid Or Not :
Valid



Case V :


 Parent{     
      synchronized m1(){}
}
Child extends Parent {
      non-
synchronized m1(){}
}



Valid Or Not :
Valid

Case VI :


Parent{      
     non-synchronized m1(){}
 }
Child extends Parent {
     
synchronized m1(){}
}


Valid Or Not :
Valid



Case VII :


Parent{  
      native m1(){}
}
Child extends Parent {
      
non-native m1(){}
}





Valid Or Not :
Valid

Case VIII :

Parent{      
      non-native m1(){}
}
Child extends Parent {
       
native m1(){}
}

Valid Or Not :
Valid

Case IX :

Parent{      
       void m1(){}
}
Child extends Parent {
       public
 void m1(){}
}


Valid Or Not :
Valid

Case X :

Parent{      
      public  void m1(){}
}
Child extends Parent {
     
void m1(){}
}

Output :
error: m1() in Child cannot override m1() in Parent
attempting to assign weaker access privileges; was public

Note : While overriding we can't reduce scope of access modifier , but we can increase the scope.  private < default < protected < public   
Benefit of this rule is , because of overriding outside members should not be affected . So because of this reason we can increase the scope but not decrease.

Parent        public             protected                  default                                    private
                      |                          |                              |                                              |
Child          public            protected/public        default/protected/public     overriding is not applicable


No comments:

Post a Comment