Sandy Drake
Sandy Drake

Reputation: 1

Overridden private method is causing exception in accessing subclass public method in Java

The below program is giving compilation error in line "obj.method()" inside the main method. The error is "The method method() from the type Superclass is not visible". From my understanding it should be able to access public method of subclass. can anyone explain the concept behind it?

class Superclass{

private void method(){
    System.out.println("Inside superclass method");
}

}

public class MyClass extends Superclass{

     public void method(){
        System.out.println("Inside subclass method");
    }

    public static void main(String s[]){

        Superclass obj = new MyClass();
        obj.method();

    }
}

Upvotes: 0

Views: 100

Answers (3)

Vineet Singla
Vineet Singla

Reputation: 1677

obj has reference of SuperClass. So it can only see SuperClass methods which are protected,default or public.
Private methods are visible only inside the class.

No Overriding happens here.

Upvotes: 0

NilsH
NilsH

Reputation: 13821

method is declared private in Superclass. private means that it will only be accessible within that class. If you want subclasses to be able to access it (or override it), you have to declare it protected instead.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500535

From my understanding it should be able to access public method of subclass.

Yes, but only when the compile-time type of the expression you're calling it on is that subclass.

So if you change your code to:

MyClass obj = new MyClass();

then it should be fine. Currently, the compile-time type of obj is just Superclass, which doesn't have a public method method.

Also note that MyClass.method does not override Superclass.method. A call to method() within Superclass would only call Superclass.method() even if the actual type of the object was MyClass.

Upvotes: 3

Related Questions