Tuesday, February 20, 2007

Java Package Protected Methods

Today, i was coding an Java app, and tried to extend an abstract class contained in other package. Lets assume this is the package hierarchy:

-Trial
- Trial.SubTrial

And in the package Trial i had this abstract class


package trial;
public abstract class Trial {

public abstract void function1();
public abstract void function2();

void function3(){
System.out.println("BLA");
}

}


And now, in the subTrial package i wanted to extend this class. This was what i did


package trial.subTrial;
import trial.Trial;

public class SubTrial extends Trial{

public void function1(){}
public void function2(){}

}


Seemed pretty straightforward, however a strange error was occurring, the compiler was telling me that i was not overriding the function1 and function2 methods (and, shit, i fucking was ). I looked for this, and in the java foruns i found the answer to this: Java Package Protected Methods (thanks zadok)

It seems that if you do not explicitly write in the class that the abstract method is public no one can override it. Ok, i understand the security logic behind the mechanism, but can anyone explain me what's the use of an abstract method if you cannot override it??

2 comments:

Anonymous said...

If you do not explicitly write a method's access level (public, protected, or private), then it will default to package-private.

The public access level means that the member (method or variable) is accessible anywhere.

The protected access level means that the member is accessible to any class inside the same package or any subclass (your extension SubTrial) where it is declared.

The private access level means that the member is only accessible to this class (not subclasses) where it is declared.

The package-private level means that the member is accessible to any class inside the same package where it is declared.

In your case, you could have declared the method as protected abstract, meaning that your subclass, SubTrial, could overwrite it, while not introducing it into the API. The advantage of NOT introducing it into the API is that you can delete or rename that method and outside classes would not be affected. By choosing to make the method public abstract it is now part of the API and all subclasses must also set the visibility to public because the visibility of the method cannot be reduced.

To answer your question, "can anyone explain me what's the use of an abstract method if you cannot override it??" You cannot create an abstract method that cannot be overridden, you can only create an abstract method that cannot be overridden by a subclass that is declared in a different package. The only reason that you cannot override it is because the access level given does not allow the subclass to see the method.

Anonymous said...

Man you saved me a big headache. Thanks!