【问题标题】:java static binding and polymorphismjava静态绑定和多态
【发布时间】:2014-09-14 06:13:28
【问题描述】:

我对下面的静态绑定示例感到困惑。我认为S2.x 和S2.y 显示静态绑定,因为它们根据s2 的静态类型打印出字段。并且S2.foo() 使s2 在超类中调用foo 方法,因为foo 在子类中没有被覆盖。

但是对于S2.goo(),它不应该调用Test1 子类中的goo() 方法吗?就像它的多态性?怎么会是静态绑定?看起来S2.goo() 调用了超类goo() 方法并打印出=13。非常感谢您提前提供的帮助!

public class SuperClass {
  public int x = 10; 
  static int y = 10; 
protected SuperClass() { 
     x = y++; 
 } 
 public int foo() { 
     return x; 
 } 
 public static int goo() { 
     return y; 
 } 
}

和子类

public class Test1 extends SuperClass {
 static int x = 15;
 static int y = 15;
 int x2= 20; 
 static int y2 = 20; 

 Test1() 
 { 
     x2 = y2++; 
 } 
 public int foo2() { 
     return x2; 
 } 
 public static int goo2() { 
     return y2; 
 } 

public static int goo(){
     return y2;
 }

public static void main(String[] args) {

    SuperClass s1 = new SuperClass();
    SuperClass s2 = new Test1();
    Test1 t1 = new Test1();

    System.out.println("S2.x = " + s2.x); 
    System.out.println("S2.y = " + s2.y); 
    System.out.println("S2.foo() = " + s2.foo()); 
    System.out.println("S2.goo() = " + s2.goo());
 }
}

【问题讨论】:

    标签: java inheritance binding static polymorphism


    【解决方案1】:

    在 Java 中,静态变量和方法不是多态的。你不能指望静态字段的多态行为。

    【讨论】:

    • 添加到这个调用 s2.goo() 不是对对象的调用,而是对 s2 引用的类变量(即 SuperClass)的调用。如此有效地调用超类方法,而与底层对象无关
    【解决方案2】:

    静态方法不能被覆盖,因为它们会在编译时与类绑定。 但是,您可以像这样隐藏类的静态行为:

    public class Animal {
       public static void foo() {
        System.out.println("Animal");
       }
    
        public static void main(String[] args) {
           Animal.foo(); // prints Animal
           Cat.foo(); // prints Cat
        }
    }
    
    class Cat extends Animal {
       public static void foo() {  // hides Animal.foo()
         System.out.println("Cat");
       }
    } 
    

    输出:

    Animal
    Cat
    

    请参阅link 以了解 Java 中的方法隐藏。 另外,请注意不要在实例上调用静态方法,因为它们会绑定到 Class 本身。

    【讨论】:

    • 甜蜜。谢谢!那么静态方法是根据变量的静态类型调用的吗?我的意思是在你的例子中,如果我们创建 Animal monster = new Cat(),那么 monster.foo() 仍然会打印出“animal”?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-27
    相关资源
    最近更新 更多