Hi All ,
In previous post we checked how co-variant can be used as a return type of overridden methods. Now in this post we checked that how private method works in inheritance.
public class InheritanceDemo1 {
public static void main(String [] args){
Child child = new Child();
child.m1();
}
}
class Parent {
private void m1(){
System.out.println("This is parent class m1 method");
}
}
class Child extends Parent {
private void m1(){
System.out.println("This is child class m1 method");
}
}
public class InheritanceDemo1 {
public static void main(String [] args){
Child child = new Child();
child.m1();
}
}class Parent {
public final void m1(){
System.out.println("This is parent class m1 method");
}
}
class Child extends Parent {
public void m1(){
System.out.println("This is child class m1 method");
}
}
In previous post we checked how co-variant can be used as a return type of overridden methods. Now in this post we checked that how private method works in inheritance.
Case I :
If we make private method in Parent class and try to override this method in Child class .Then it would not available for Child class.And if we create another method with same name and same return type , then overriding concept will not takes place , and we will get compile time error.Let's take a look:
public static void main(String [] args){
Child child = new Child();
child.m1();
}
}
class Parent {
private void m1(){
System.out.println("This is parent class m1 method");
}
}
class Child extends Parent {
private void m1(){
System.out.println("This is child class m1 method");
}
}
Output :
error: m1() has private access in Child
Explanation:
In this example we can see that the Parent class private methods not available to the child.Hence overriding concept not applicable for private methods.
Case II :
If we make final method in Parent class and try to override this method in Child class .Then it would not available for Child class.Let's take a look:
public static void main(String [] args){
Child child = new Child();
child.m1();
}
}class Parent {
public final void m1(){
System.out.println("This is parent class m1 method");
}
}
class Child extends Parent {
public void m1(){
System.out.println("This is child class m1 method");
}
}
Output :
error: m1() in Child cannot override m1() in Parent
overridden method is final
No comments:
Post a Comment