简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM