2013-11-25 176 views
1
class Base 
{ 
     int x=1; 
    void show() 
    { 
     System.out.println(x); 
    } 
} 
class Child extends Base 
{ 
    int x=2; 
    public static void main(String s[]) 
    { 
     Child c=new Child(); 
     c.show(); 
    } 
} 

输出为1 的方法显示在基类,但继承优先级应给予局部变量,因此输出应该是2或者是它的编译器之前,它隐含的前缀超? ?爪哇 - 继承

+1

多态性并不适用于各个领域。 –

回答

1

由于您不是覆盖show方法中的Child,因此将使用Base的版本。因此它不能看到您在Child中定义的x变量。你的IDE(如果你使用的话)应该给你一个警告,说你“隐藏了一个领域”。

在实例化对象后,您可以通过设置对象的x来实现预期的功能。尝试:

class Base 
{ 
    int x = 1; 

    void show() {   
     System.out.println(x); 
    } 
} 

class Child extends Base 
{ 
    public static void main(String s[]) { 

     Child c = new Child(); 

     c.show(); 
     c.x = 2; 
     c.show(); 
    }  
} 

这应产生1,然后2

编辑:请注意,当x场是从main功能来访问这个才起作用。

2

不,这是因为孩子没有覆盖show()方法。唯一可用的是Base的一个,它显示了它的x版本。

尝试这种方式 - 它会显示2:

class Base 
{ 
     int x=1; 
    void show() 
    { 
     System.out.println(x); 
    } 
} 
class Child extends Base 
{ 
    int x=2; 
    public static void main(String s[]) 
    { 
     Child c=new Child(); 
     c.show(); 
    } 
    void show() 
    { 
     System.out.println(x); 
    } 
} 
0

Base类不知道Child类,所以show()方法永远不会调用该变量从它的子类。

所以,如果你想显示从子类中的xChild类重新实现它覆盖show()方法。

1

有了一个显示方法

class Child extends Base 
{ 
    public Child(int x) 
    { 
     super(x); // Assumes a constructor in the parent that accepts an int. 
     // or 
     super.x = x; 
    } 
} 

然后你只需要一个show()方法。

带有两个显示方法

您覆盖超类的功能,在它的子类,如下所示:

class Child extends Base 
{ 
    public void show() 
    { 
     // OVerrides the code in the superclass. 
     System.out.println(x); 
    } 
} 

你应该更喜欢哪个?

你试图重写功能,所以你应该有利于第二个选项。