开发者

Java private method override

I came across this scenari开发者_运维问答o. 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:

  • the type of the main1 variable is Main (not Main1)
  • so you can only call methods of that type
  • the only possible method called print that accepts a List<String> on Main is the private one
  • the calling code is inside the class Main so it can call a private method in that class

Therefore Main.print(List<String>) will be called.

Note that changing the type of main1 to Main1 will result in the other print(List<String>) method being called.


If you want to be able to override your print method you have to declare it public:

public class Main {

   public void print(List<String> string) {
   }

}

Otherwise it will call your private method without looking for the implementation in a derived class .


Private method is not inherited and method overriding does not happened in your code. You can see this by putting @Override annotation in Main1.print() method. If you put that annotation, compile error generated.

Main.java:17: method does not override or implement a method from a supertype
        @Override
        ^
1 error

In your case, Main1.print() and Main.print() are different and not related each other(no overriding, no overloading). So if you specify main1 as Main, Main.print() will be called. And if you specify main1 as Main1, Main1.print() will be called.


Your main1 is a type of Main but instantiated with as Main1! It's OK since it is a subclass for Main. However, when you call the print method (BTW, it should be main1.print(list);) it will call the private method in the Main class! If you change the visibility of your method to protected or public, in this case print method in the Main1 class will be called because of polymorphic behavior of your instantiated object (remember, it is after all a Main1 object based on the code that you've provided!)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜