Search code examples
javaclassobjectinheritanceinstances

Understanding execution flow of this Java programme


I'm new at learning Java can anyone explain me the execution flow of the following code? I'm quite confused with the output.

This is the code:

public class MainClass {
    public static void main(String[] args) {
        car c = new car();
        vehicle v = c;
        /* I am unable to understand what's happening while printing the values using the objects of the different classes*/

        System.out.println("|" + v.getModelName()
                + "|" + c.getModelName()
                + "|" + v.getRegNo() + "|" + c.getRegNo() + "|");
    }
}

class vehicle {
    public static String getModelName() {
        return "Volvo";
    }

    public long getRegNo() {
        return 12345;
    }
}

class car extends vehicle {
    public static String getModelName() {
        return "Toyota";
    }

    @Override
    public long getRegNo() {
        return 54321;
    }
}

Solution

  • Object creation

    1. You are creating car instance ( new car())
    2. Add new object pointer to variable c
    3. Copy content of variable c to variable vehicle ( which point to car object)

    Method call flow

    When you are call static function on object it will not apply inheritance rules, so in call to v.getModelName() Java Virtual Machine call method in class vehicle.

    But when you are call car() object with vehicle pointer (v variable) getRegNo method of class vehicle will call and also when you are using car pointer (c variable) getRegNo method of class vehicle will call.

    edite suggestion form comment:

    This ability called "Polymorphism": here you can find good tutorial. "Polymorphism" is definitely as important a concept as "inheritance" and "encapsulation'.