扩展变量和协变返回类型
我正在测试协变返回类型并遇到了这个问题。
class Vehicle {
int i = 3;
}
class Car extends Vehicle{
int i = 5;
public Car returningCar(){
System.out.println("Returning Car");
return new Car();
}
public Vehicle returningCarInVehicle(){
System.out.println("Returning CarInVehicle");
return new Car();
}
}
public class ScjpTest{
public static void main(String[] args){
Car car = new Car();
Vehicle vehicleCar = car.returningCar();
Vehicle vehicleCar2 = car.returningCarInVehicle();
System.out.println("vehicleCar " + vehicleCar.i);
System.out.println("vehicleCar2 " + vehicleCar2.i);
}
}
上面的输出是 Returning Car
Returning
CarInVehicle
vehicleCar 3
vehicleCar2 3
我不明白为什么输出是 3。我期望在这两个实例中输出都是 5,因为在运行时 JVM 使用实际对象而不是引用。
谢谢
I was testing out covariant return types and came across this problem.
class Vehicle {
int i = 3;
}
class Car extends Vehicle{
int i = 5;
public Car returningCar(){
System.out.println("Returning Car");
return new Car();
}
public Vehicle returningCarInVehicle(){
System.out.println("Returning CarInVehicle");
return new Car();
}
}
public class ScjpTest{
public static void main(String[] args){
Car car = new Car();
Vehicle vehicleCar = car.returningCar();
Vehicle vehicleCar2 = car.returningCarInVehicle();
System.out.println("vehicleCar " + vehicleCar.i);
System.out.println("vehicleCar2 " + vehicleCar2.i);
}
}
The output to the above is Returning Car
Returning
CarInVehicle
vehicleCar 3
vehicleCar2 3
I dont understand why the output is 3. I was expecting the output to be 5 in both instances because at runtime the JVM uses the actual object not the reference.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
字段不是虚拟的/可覆盖的/等等。它们将根据引用的编译时类型进行解析,在本例中为
Vehicle
。此代码将打印“vehicleCar2 5”:
因为强制转换生成编译时类型
Car
的表达式。Fields aren't virtual/overrideable/etc. They will be resolved according to the compile-time type of the reference, which in this case is
Vehicle
.This code would print "vehicleCar2 5":
since the cast makes the expression of compile-time type
Car
.您需要使用方法来获得所需的多态行为(这也是 通过将成员变量设置为私有并提供公共 setter 和 getter 方法来封装成员变量)
You need to use methods to get the polymorphic behaviour you're after (it's also a best practice to encapsulate member variables by making them private and providing public setter and getter methods)
您的问题是正确的,但多态性仅适用于函数。它不适用于变量。执行变量时它将采用引用类型,而不是引用所指向的确切对象类型。希望您能得到它。
Your question is correct but Polymorphism works for functions only. It will not work for variable. It will take the reference type while executing variable not the exact object type that reference is pointing to.hope you will get it.