简体   繁体   中英

java static binding and polymorphism

I am confused with the static binding example below. I reckon that S2.x and S2.y shows static binding as they prints out the fields according to s2 's static type. And S2.foo() makes s2 call the foo method in the super class, as foo is not over ridden in the subclass.

However with S2.goo() , isn't it supposed to call the goo() method in the Test1 subclass? Like it's polymorphism? How come it's static binding? It looks like S2.goo() calls the Super Class goo() method and prints out =13 . Many thanks for your help in advance!

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; 
 } 
}

and SubClass

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());
 }
}

In Java static variables and methods are not polymorphic. You can't expect polymorphic behavior with static fields.

Static methods can not be overridden, because they get bind with the class at compile time itself. However, you can hide the static behavior of a class like this:

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");
   }
} 

Output:

Animal
Cat

Refer link for method hiding in Java. Also, take care that static method should not be called on instance as they get bind to Class itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM