Search code examples
javadynamic-bindingstatic-binding

Java: static- vs. dynamic binding (again)


i've read a lot of blogs, tutorials & co but i don't get something about the dynamic binding in java. When i create the object called "myspecialcar" it's creates an object from the class "car" as type of the class vehicle as a dynamic binding right? So java know that when i execute the method myspecialcar.getType() i have a car object and it execute the method from the class car. But why i got the type from the class vehicle? Is that because the variable from the class vehicle (type) is a static binding?

Regards,

Code:

public class vehicle {
    String type = "vehicle";

    public String getType(){
        return type;
    }
}

public class car extends vehicle {
    String type = "car";

    public String getType(){
        return type;
    }
}

public class test {
    public static void main (String[] args){
        vehicle myvehicle = new vehicle(); // static binding
        car mycar = new car(); // static binding
        vehicle myspecialcar = new car(); //dynamic binding

        System.out.println(myspecialcar.getType());
        System.out.println(myspecialcar.type);
        System.out.println(myspecialcar.getClass());
    }
}

Output:

car
vehicle
class car

Solution

  • You do not override class variables in Java you hide them.

    Overriding is for instance methods. Hiding is different from overriding.

    In your case you are hiding the member variable of super class. But after creating the object you can access the hidden member of the super class.