我正在努力理解 Java 的变量隐藏方法重写继承概念。
案例一:
class Car{
public int gearRatio = 8;
public String accelerate() { return "Accelerate : Car"; }
}
class SportsCar extends Car{
public int gearRatio = 9;
public String accelerate() { return "Accelerate : SportsCar"; }
public static void main(String[] args){
Car c = new SportsCar();
System.out.println( c.gearRatio+" "+c.accelerate() );
}
}
输出:8 加速:跑车。
案例二:
public class TestClass{
public static void main(String args[ ] ){
A o1 = new C( );
B o2 = (B) o1;
System.out.println(o1.m1( ) );
System.out.println(o2.i );
}
}
class A { int i = 10; int m1( ) { return i; } }
class B extends A { int i = 20; int m1() { return i; } }
class C extends B { int i = 30; int m1() { return i; } }
输出:30、20
因此,如果我理解正确的话,除非显式调用子类变量,否则总是会调用父类(super class)变量。但对于调用子类重写方法的方法则相反,除非显式调用父类(super class)。
我认为变量和方法应该工作相同,否则在创建具有相同变量的子类时应该出现编译错误。
谁能解释一下这是否正确以及为什么 java 会这样工作。
最佳答案
I would think variables and methods should work the same or there should be a compile error when creating sub classes with the same variables.
嗯,这根本不是 Java 的工作方式。
变量不以多态方式处理——没有“覆盖”变量的概念。然而,方法是以多态方式处理的。 行为可以专门化,但状态不能。
请注意,如果您的变量是私有(private)的(它们几乎总是应该是私有(private)的),那么这种情况永远不会可见。
关于Java 变量阴影方法覆盖概念,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12078751/