开发者

Extending variables and covariant return types

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


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":

System.out.println("vehicleCar2 " + ((Car)vehicleCar2).i);

since the cast makes the expression of compile-time type Car.


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)

    class Vehicle {

        private int i = 3;

        protected Vehicle(int i) {
            this.i = i;
        }

        public int i() {
            return i;
        }
    }
    class Car extends Vehicle{

        public Car() { 
            super (5);
        }

        public Car returningCar(){
            System.out.println("Returning Car");
            return new Car();
        }

        public Vehicle returningCarInVehicle(){
            System.out.println("Returning CarInVehicle");
            return new Car();
        }
    }

    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());

    }


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜