Inheritance and public/private methods Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Inheritance and public/private methods without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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?

Answer

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.

We are here to answer your question about Inheritance and public/private methods - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji