-2

One.java

public class One {

    private void run() {
        System.out.println("one");
    }

    public void start() {
        this.run();
    }
}

Two.java

public class Two extends One {
    public void run() {
        System.out.println("two");
    }
}

Main.java

public class Main {
    public static void main(String[] args) {
        Two t = new Two();
        t.start();
    }
}

Output: one

But if I declare the run method public in the One class I get "two" as output.

It is pretty unpredictable, how does this work?

Makoto
  • 96,408
  • 24
  • 164
  • 210
zer0uno
  • 6,150
  • 10
  • 47
  • 70

3 Answers3

6

The run method in Two will not be overriding the private method in One, because it is private and inaccessible to any class outside One.

Once the method is marked as public, the inheritance system takes place, and run is invoked from start in One (as the method is not overridden), but then resolved dynamically (at runtime) as Two's run.

My advice, use the @Override annotation to make sure at compile-time that a method is properly overridden.

Also, you seem to be playing with start and run methods: remember you need to extend Thread or implement Runnable for the JVM to recognize your classes as Runnables.

Mena
  • 45,491
  • 11
  • 81
  • 98
1

In Java, private methods are NOT visible to subclasses. Protected methods ARE.

In the class Two you did not override the start() method, therefore t.start() uses One.start() which calls One.run() which prints "one".

If you change the run() method to public or protected the Two class will override it and calling t.start() will end up calling the version declared in Two.

In "flowchart" form:
When run is private

Two.start() -> not defined! -> go to superclass -> One.start() -> run() -> One.run()

When run is public or protected

Two.start() -> not defined! -> go to superclass -> One.start() -> run() -> run() is overridden by subclass -> go to subclass -> Two.run()

Arc676
  • 4,196
  • 3
  • 26
  • 41
0

Because run is private in One, it is not dynamically linked, nor inherited. The run in Two does NOT override the run in One

ControlAltDel
  • 28,815
  • 6
  • 42
  • 68