DarudeSamstorm
DarudeSamstorm

Reputation: 171

Override private method in superclass - is there a way?

I know that the method would be protected not private if what I want to do was intended, however I want to make my own PriorityQueue that will need to call siftUp a few more times. I can't edit the declaration of the field as PriorityQueue is a part of the java library, so I'm looking for another way to call it. Is the only thing I can do copy the whole class from the library and change it to my needs?

Upvotes: 2

Views: 1248

Answers (1)

Sometowngeek
Sometowngeek

Reputation: 607

There is no way to override the superclass's private method, unfortunately.

According to Oracle's documentation on Controlling Access to Members of a Class, the private method is only for the class itself to access.

Here's the table of the Superclass's visibility to Subclass:

Superclass and subclass

Superclass's member visibility to subclass

I believe they offer the developers to implement the "least privilege" principle by offering the private visibility so there would be no way for it to be accessible anywhere outside the class it was created in.

If you wanted to be able to override it, you should make it protected or don't give it any modifier (considered "Package access" level).

Here is an example:

package this.silly.package;

public class Foo() {
    void thisAction() {
        // do stuff...
    }

    private void somethingElse() {
        // Do secret stuff.
    }
}
package this.silly.package;

public class Bar extends Foo() {

    // This will work 
    // because this class is in the same package as Foo.
    @Override
    void thisAction() {
        // Do something else
    }

    // This will not work
    // because Foo made this method private,
    // so it is only accessible by Foo.
    @Override
    private void somethingElse() {
        // Please don't do secret stuff. You might drive me crazy!
    }
}

Upvotes: 2

Related Questions