-4
public class A {
    private void getHello(){
        System.out.println("Prints A");
    }
}
class B extends A {
    public void getHello(){
        System.out.println("Prints B");
    }
}
class Test{
    public static void main(String[] args) {
        A a = new B();
    }
}

I am creating private method in class A
creating public method with same name in class B by extending class A
Even after creating object for B with A reference
why I am not able to call getHello()?

Michael
  • 41,989
  • 11
  • 82
  • 128
Praveenkumar
  • 119
  • 3
  • 12

3 Answers3

1

getHello method is private for class A and you may call it only from this class.

Even if create an instance of class A in some other class you will not be able to access getHello() method. This is also invalid code.

class Test {
    public static void main(String[] args) {
        A a = new A();
        a.getHello();
    }
}

Here is Java documentation.

djm.im
  • 3,295
  • 4
  • 30
  • 45
1

Be declaring it as a type of A you are losing the implementation details of B although there still there.

 A a = new B(); // a.getHello() is not accessible because it looks it up in A
 B b = new B(); // a.getHello() is accessible because it calls it in B

Even if the getHello() method would be public in A it would still call it for the instance of B.

Murat Karagöz
  • 35,401
  • 16
  • 78
  • 107
1

As Java Language Specification (https://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html#jls-6.6) states:

A private class member or constructor is accessible only within the body of the top level class (§7.6) that encloses the declaration of the member or constructor. It is not inherited by subclasses.

When you create a reference to object of A class it is not possible to get access to this method from outside of this class in your case.

Przemysław Moskal
  • 3,551
  • 2
  • 12
  • 21