我正在努力用Java了解Variables Shadowed Methods Overriden继承概念.
情况1:
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加速:跑车.
案例2:
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
因此,如果我理解正确,除非明确调用子类变量,否则始终调用超类变量.但对于调用子类重写方法的方法则相反,除非显式调用超类.
我认为变量和方法应该相同,或者在创建具有相同变量的子类时应该存在编译错误.
有人可以解释这是否正确以及为什么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的工作方式.
变量不是多态处理的 – 没有“覆盖”变量的概念.然而,方法是多态的.行为可以是专门的,但不是状态.
请注意,如果您的变量是私有的,因为它们几乎总是应该是,那么情况永远不可见.
标签:java,inheritance,variables,override,shadowing
来源: https://codeday.me/bug/20190714/1455446.html