Error : Weaker Access Privileges

Posted by

Ahh so you are getting Weaker Access privileges error , Its really a tricky interview question , I found it really interseting.

So what do you think , what will be the output of following program , Lets guess

 class Super{  
      protected void print(){  
           System.out.println("Print in super");  
      }  
 }  
 class Sub extends Super{  
      private void print(){  
           System.out.println("Print in sub");  
      }  
      public static void main(String ar[]){  
      Super sub= new Sub();  
      sub.print();  
      }  
 }  

Before getting this error “Weaker Access Privileges” , my answer was “Print in sub” , but what I got

 

Sub.java:9: error: print() in Sub cannot override print() in Super
         void print(){
              ^
  attempting to assign weaker access privileges; was protected
1 error

So what is Weaker Access Privileges , It occurs when you try to override a higher privileged access method with lower privilege access.


Explanation :  So in above code we are trying to override protected method with the private specifier, as we know private specifier has only class level access so its lower privileged then protected and thats why its giving error.

Now take another example

 interface Java{  
      void print(int t);   
 }  
 public class Java2Career implements Java {  
      public static void main(String [] args){  
           new Java2Career().print(5);  
      }  
      void print(int s) {  
      System.out.println("s " + s);  
      }  
 }  

You would have noticed that not any access specifier is specified to both methods means It should print 5 as output but no it will also give the error , the same error, WHY?

Because all the methods and variable defined in interface are by default public so when we are overriding the method with no access specifier in subclass “Java2Career” , We are trying to give lower access privilege.

I hope you have enjoyed it , Thanks for reading , any Suggestions are always welcome , If  I am wrong anywhere, I will update my post with the suggestion in comments.

You may also like following Interview Questions:

  1. Some tips to solve your java technical test paper
  2. Transient and volatile modifier (Most asked in Interviews)
  3. Interview Questions of Java for Freshers
  4.  A program to check String is palindrom or not?
  5.  What is Intern String?

2 comments

Leave a Reply