Calling methods inside Constructor

java

Solution

The reason the child method is called is because virtual method dispatch is the norm in Java. When you call the method, it decides which method to actually call at runtime based on the actual type of the object.

As for why it prints 0, that's because `i` hasn't been set to 45 yet. Each field is initialized with a default value for that type, `0` in the case of integers. When you write `int i = 45`, the compiler will generate code in the constructor to set `i = 45`. But it places this code after the parent constructor is called. Therefore, you're printing the variable before it is initialized with its intended value.

Problem

Below I am Having Two classes.Parent and Child. The Child class inherits from Parent class .In Parent class constructor I am calling print() method of Parent class. When I create Object for Child class in main() method the Parent class constructor runs and the Child class print() method is called instead of Parent class print() method. Q1. Why this Happens. Q2. Why the value of i is 0 ``` public class Sample { public static void main(String[] args) { Child objChild = new Child(); objChild.print(); } } class Parent { void print() { System.out.println("i Value"); } Parent() { print(); } } class Child extends Parent { int i = 45; void print() { System.out.println("i Value = "+i); } } ``` OP ``` i Value = 0 i Value = 45 ```

Original source