Thursday, May 19, 2011

Published 5/19/2011 by with 2 comments

attempting to assign weaker access privileges

Java error "attempting to assign weaker access privileges" can happen when we override a superclass method in the subclass if the access modifier is not correctly chosen.

See the sample code below:

public class SuperClass
{
public void display()
{
System.out.println("this is super class");
}
}


public class Subclass extends SuperClass
{
private void display()
{
System.out.println("this is subclass");
}
}

If the above Subclass is compiled the error message will be:
display() in Subclass cannot override display() in SuperClass; attempting to assign weaker access privileges; was public

Let's understand the error message:
The method display has public access in the SuperClass and private access in the Subclass, that means when overriding this method, a weaker access privilege is going to be set (private is weaker access privilege than public).

So we need to know the allowed access modifier in the subclass for method overriding. The table below shows this:


Access modifier in super class method
Allowed access modifier for overriding
private
private, package, protected, public
package
package, protected, public
protected
protected, public
public
public


    email this       edit

2 comments:

  1. public class Subclass extends SuperClass
    {
    private void display()
    {
    System.out.println("this is subclass");
    }
    }


    http://tehapps.com/

    ReplyDelete
  2. class OuterClass
    {
    //...
    }
    This is true for an interface also. An interface can only be public or package not private or protected.

    http://wikitechy.com/

    ReplyDelete