簡體   English   中英

java靜態綁定和多態

[英]java static binding and polymorphism

我對下面的靜態綁定示例感到困惑。 我認為S2.xS2.y顯示靜態綁定,因為它們根據s2的靜態類型打印出字段。 S2.foo()使s2調用超類中的foo方法,因為foo沒有在子類中被覆蓋。

但是,使用S2.goo() ,是否應該在Test1子類中調用goo()方法? 喜歡多態嗎? 怎么是靜態綁定? 看起來S2.goo()調用Super Class 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中,靜態變量和方法不是多態的。 您不能期望靜態字段具有多態行為。

靜態方法不能被覆蓋,因為它們在編譯時本身就與類綁定。 但是,您可以隱藏此類的靜態行為,如下所示:

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

請參閱鏈接以獲取Java中的方法隱藏。 另外,請注意不要在實例上調用靜態方法,因為它們會綁定到Class本身。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM