假设我们有代码:public class Solution {private String name;private String surname;Solution(String name, String surname) { this.name = name; this.surname = surname;}private String getPrivate() { return name; }public String getPublic() { return surname; }private void sout() { new Solution("Anonim private", "Anonim public") { void printName() { System.out.println(getPrivate()); // Main private //System.out.println(this.getPrivate()); // can't compile System.out.println(super.getPrivate()); // Anonym private System.out.println(Solution.this.getPrivate()); // Main private System.out.println("\n"); System.out.println(getPublic()); // Anonym public System.out.println(this.getPublic()); // Anonym public System.out.println(super.getPublic()); // Anonym public System.out.println(Solution.this.getPublic()); // Main public } }.printName();}public static void main(String[] args) { new Solution("Main private", "Main public").sout();}}评论 - 我们的输出(通过 Intellij 想法)问题:为什么super.getPrivate()返回字符串"Anonym private"?如果我们查看 Java 文档,我们会看到如果您的方法覆盖了其超类的方法之一,则可以通过使用关键字 super 来调用被覆盖的方法。但是在这种情况下获得了另一个含义super:内部类的实例。您可以检查它添加:System.out.println(super.getClass());System.out.println(this.getClass());
添加回答
举报
0/150
提交
取消