Thursday, May 19, 2011



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




If the above solutions do not work for you. Please comment below giving your code. I'll try to respond.

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