0

I tested the following code in Java to see what happens when I rewrite the implementation of a private method.

/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */

class Superclass {

    public void runDo() {
        this.doSomething();
    }

    private void doSomething() {
        System.out.println("from Superclass");
    }
}

class Subclass extends Superclass {

    private void doSomething() {
        System.out.println("from Subclass");
    }

}

class Runner {

    public static void main(String[] args) {

        Superclass superSuper = new Superclass();
        Superclass superSub = new Subclass();
        Subclass subSub = new Subclass();

        superSuper.runDo();
        superSub.runDo();
        subSub.runDo();
    }
}

The output for the above sample is

from Superclass

from Superclass

from Superclass

While I expected something like

from Superclass

from Subclass

from Subclass

Can someone please explain this behaviour and why it makes sense?

kapad
  • 611
  • 2
  • 11
  • 27

2 Answers2

1

You cannot override a private method. You must declare it default, protected or public for the behaviour that you want.

I suggest reading the Java documentation on access modifiers

tddmonkey
  • 20,798
  • 10
  • 58
  • 67
1

It does not work because you cannot override private methods.

You did not actually override your method. In Superclass you render doSomething() as private, hence it is not visible (nor overridable) in children classes.

Try setting access modifier to protected, public or default.

darijan
  • 9,725
  • 25
  • 38