Computer Science, asked by wahid5192, 1 year ago

If the access specifier of the display method in super class is protected, then what could be the valid specifier for the overriding display method in sub class?

Answers

Answered by qwtiger
2

Answer:

If the access specifier of the display() in super class is protected, then  the valid specifier for the overriding display() in sub class could be either 'public' or 'protected'.

Because the rule says:

The method of sub class which is overridden from the super class cannot have weaker access specifier than the super class method.

For example:

class A {  

   protected void display()  

   {  

  System.out.println("Hello");  

   }  

}    

public class B extends A {    

   void display()  

   {  

       System.out.println("Hello");  

   }  

   public static void main(String args[])  

   {  

       B b = new B();  

       b.display();  

   }  

}

Output: Compile Time Error

Because in the super class A we have used the display() whose access specifier is protected. While overriding the method we didn't use any access specifier so it used the 'default' access modifier which is more restrict than protected therefor it shows compile time error.

The correct would be:

class A {  

   protected void display()  

   {  

       System.out.println("Hello");  

   }  

}  

 

public class B extends A {  

   public void display()  

   {  

       System.out.println("Hello");  

   }  

 

   public static void main(String args[])  

   {  

       B b = new B();  

       b.display();  

   }  

}  

Output:

Hello

Answered by ronakbhavsar495
0

Answer:

According to the access specifier method of over riding display in the sub class- the overridden method must not have any weaker access than super class. So, if the super class is protected, then the interface should be public (taken by default) and this would override the same specifier in the sub class.

Similar questions