java的静态绑定和多态 [英] java static binding and polymorphism

查看:125
本文介绍了java的静态绑定和多态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很困惑与下面的静态绑定的例子。我估计 S2.x S2.y 显示静态绑定,因为他们根据<$ C打印出的字段$ C> S2 的静态类型。和 S2.foo(),使 S2 致电在超级类,如方法还没有结束在子类缠身。

然而,随着 S2.goo(),是不是应该叫咕()方法在测试1 子?喜欢它的多态?为什么它的静态绑定?它看起来像 S2.goo()调用父类咕()方法,并打印出 = 13 。非常感谢您的帮助提前!

 公共类父类{
  公众诠释x = 10;
  静态INT Y = 10;
保护父类(){
     X = Y ++;
 }
 公众诠释美孚(){
     返回X;
 }
 公共静态INT咕(){
     返回是;
 }
}

和子

 公共类Test1的扩展父类{
 静态INT X = 15;
 静态INT Y = 15;
 INT X2 = 20;
 静态INT Y2 = 20; Test1的()
 {
     X2 = Y2 ++;
 }
 公众诠释foo2的(){
     返回X2;
 }
 公共静态INT goo2(){
     返回Y2;
 }公共静态INT咕(){
     返回Y2;
 }公共静态无效的主要(字串[] args){    超类S1 =新的父类();
    超类S2 =新的Test1();
    test1的T1 =新的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静态变量和方法是不是多态。你不能指望用静态字段的多态行为。

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 s2call 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.

这篇关于java的静态绑定和多态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆