我有2个班级:
public class A
{
int n = 10;
public int getN()
{
return n;
}
}
public class B extends A
{
int n = 20;
public int getN()
{
return n;
}
}
public class Test
{
public static void main(String[] args)
{
B b = new B();
System.out.println(b.getN()); //--> return 20
System.out.println(((A)b).getN()); //--> still return 20.
//How can I make it return 10?
}
}
答案 0 :(得分:5)
Java中的所有方法都是虚拟的。也就是说,没有办法从外部调用方法的“超级”版本。转换为A
将无济于事,因为它不会更改对象的运行时类型。
这可能是您最好的选择/解决方法:
class A {
int n = 10;
public int getN() {
return n;
}
public final int getSuperN() { // "final" to make sure it's not overridden
return n;
}
}
class B extends A {
int n = 20;
public int getN() {
return n;
}
}
public class Main {
public static void main(String[] args) {
B b = new B();
System.out.println(b.getN()); // --> return 20
System.out.println(((A)b).getN()); // --> still return 20.
System.out.println(b.getSuperN()); // --> prints 10
}
}
答案 1 :(得分:1)
由于多态性,这个东西不起作用。类B
仍然是类B
,即使您将其强制转换为超类。
我认为你需要这样的东西:
public class B extends A
{
int n = 20;
/**
* @return the super n
*/
public int getSuperN()
{
return super.n;
}
}
答案 2 :(得分:1)
你不能使值为“10”,因为对象的实例是针对B类的,当你进行转换时,你唯一要做的就是改变define类而不是设置对象B的值换句话说,如果你需要得到10个'像这样的东西
b = new A();
答案 3 :(得分:0)
你看到的是行动中的多态性。由于b
是B
,因此始终会调用该方法(返回20)(无论您将其转换为A
)。