首页 > 解决方案 > Java多态中的成员访问特性

问题描述

public class A {
    public int a = 10;
    public void show() {

    }
}

public class B extends A{
    public int a = 20;
    public int b = 10;

    @Override
    public void show() {
        System.out.println(this.a);
    }

    public static void main(String[] args) {
        A a = new B();
        a.show();
        System.out.println(a.a);
    }
}

看上面的代码,我使用父class A引用指向子class B object (A a = new B()),但是当我a.a(System.out.println(a.a))在main方法中打印时,它打印是因为成员变量a在父中10被赋值了一个值。但是当我在子类中重写的方法中打印时,方法打印,它打印,我很困惑。我认为结果应该是一样的。可以看到输出如下图:</p> 10class Athis.a(System.out.println(this.a))showshowthis.a (System.out.println(this.a))20

20
10

提前致谢!

标签: javapolymorphism

解决方案


在java中,只有方法被覆盖,而不是变量。因此,父类的变量不会被子类的变量覆盖。这是Java中的设计决策。其中一个问题是父类方法可以执行而不必担心子类变量......即它有助于not breaking parent classes code......

一个例子可能如下所示:

public class Parent {
  String someVar; // note this: it is "String" type
  String getSomeVar() {
  }
}

public class Child extends Parent {
  int someVar; // same name but different type, this would break the code if
  // java permit "variable overriding" feature
}

可以清楚的看到,parent 的 type 和 child 的 type 是不一样的。我想,您现在可以理解为什么变量覆盖会很危险......

更新:

@helloWorld,在阅读了您发表的最后一条评论后,您似乎误解了overriding.

特别是,我为你准备了一个例子。阅读以下带有注释的代码:

class A {
    public int a = 10;

    public void show () {
        System.out.println("Inside A: " + this.a);
    }
}

class B extends A {
    public int a = 20;
    public int b = 10;

    @Override
    public void show() {
        System.out.println("Inside B: " + this.a);
    }
}
B b = new B();
A a = b;

b.show(); // prints "Inside B: 20", it should print "20", so it's okay
a.show(); // prints "Inside B: 20", so, method in 'A' is overrided by class 'B', cause, in normal definition it should print "10"

System.out.println("value of b.a: " + b.a); // prints "value of b.a: 20", it should print '20', so it's okay
System.out.println("value of a.a: " + a.a); // prints "value of a.a: 10", it is not overrided by class 'B', but notice 'a.show()' method was overrided

所以,我想,你已经明白了,覆盖意味着:当使用something(a method/variable)byparent/super class's reference但获得在child class'swhileparent/super类的实现中定义的行为时particular method/variable,被称为覆盖......

你也可以阅读这个

关于this

this必然an object。而且它总是access只用于那个特定的,class's scopevariables/methods在 that 中声明的class。因此,要在您parent内部访问,child您需要使用super.


推荐阅读