0

The output of the program is A isn't it suppose to be B. If I change the modifier of method in Class A to public then the output is B. Can somebody explain what is going on here?

Code:

public class HelloWorld {
    public static void main(String[] args) {
        HelloWorld hw = new HelloWorld();
        hw.createInstance();
    }

    public void createInstance() {
        A b = new B();
        b.isTrue();
    }
    
    public class A {
        private void isTrue() {
            System.out.println("A");
        }
    }
    public class B extends A {
        public void isTrue() { 
            System.out.println("B");
        }
    }
}

Output: A

Hemanth
  • 11
  • 3

2 Answers2

2

If isTrue() in A was public, then isTrue() in B would override it. (Overriding means if you call a method declared in the base class, the matching method in the subclass is executed.)

In this case, since isTrue() in A is private, the two isTrue() methods are independent. Private methods are not subject to overriding.

Since you are calling isTrue() on a variable of type A, it is the isTrue() method in A that is executed. Being private does not, in this case, prevent you accessing the method, because all your code is inside one class, HelloWorld. If your classes were not inner (or nested) classes, then you wouldn't be able to call the private method from outside the class it is declared in.

khelwood
  • 55,782
  • 14
  • 81
  • 108
-1

You are creating a B instance, pointed by an A Instance. As A isTrue is private, the compiler will raise an error

If you make A.isTrue() public, as you created a B instance it will execute B isTrue method, as that method is overridden

Due your classes are inner classes, when you call isTrue pointed by A class it executes isTrue from A and does not apply the override because the methods have different visibility. When you make isTrue from A public it applies polymorphism as they have the same modifier.

The confussion is because they are inner classes, if they weren't inner classes your code won't compile

  • 1
    _As A isTrue is private, the compiler will raise an error_ -there is no compilation error [link](https://www.jdoodle.com/online-java-compiler/#&togetherjs=LB2lEOyif6) – Hemanth Jun 02 '21 at 16:40