I came across this scenario. We have a class lets say Main having a private method print. There is another class Main1 which extends Main class and redefines the print method. Since main1 is an object of Main1 class, I expect main1 print method to get called…
public class Main {
public static void main(String[] args) {
Main main1 = new Main1();
List<String> list = new ArrayList<String>();
main1.print(list);
}
private void print(List<String> string) {
System.out.println("main");
}
}
class Main1 extends Main {
public void print(List<String> string) {
System.out.println("main1");
}
}
In this case, when we run the program, it print “main”. It really confuses me as that method is private and is not even part of Main1 class.
The answer is not too hard:
main1variable isMain(notMain1)printthat accepts aList<String>onMainis the private oneMainso it can call a private method in that classTherefore
Main.print(List<String>)will be called.Note that changing the type of
main1toMain1will result in the otherprint(List<String>)method being called.