Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling methods inside Constructor

Tags:

java

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
like image 852
Java Beginner Avatar asked Apr 24 '13 05:04

Java Beginner


4 Answers

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.

like image 79
Antimony Avatar answered Nov 17 '22 05:11

Antimony


Java actually has some pretty clear rules about this. Essentially the "int i = 45" code in the subclass is an implicit part of the subclass constructor and the superclass constructor always runs first.

The order of events is:

  • Create the object and zero out all instance variables.
  • Invoke superclass initializers.
  • Invoke superclass constructor.
  • Invoke subclass initializers (int i = 45; in this example)
  • Invoke subclass constructor.

This gets really nasty when you have a final field. You could declare "i" final in your example and get the same result!

In general, invoking non-private (or at least non-final) methods in a constructor is asking for trouble and is often the source of nasty bugs. Invoking an abstract method is a really bad idea (most of the time).

like image 22
john_omalley Avatar answered Nov 17 '22 06:11

john_omalley


Java Beginner : I got your problem.. 1.When you create the object of child class at that time print() method called only in child class not in parent class even though parent class constructor called first bcoz the object is of child class Please refer the following example.

public class Test
    {
        public static void main(String[] args) 
        {
            //create the object of child class
            Child child = new Child();
        }
    }

    class Parent
    {   
        void print()
        {
            System.out.println("parent>> i ValueOne=");
        }

        Parent()
        {
            System.out.println("parent>> i ValueTwo=");
            print();
        }
    }    

    class Child extends Parent
    {
        int i = 45;


        void print()
        {
            System.out.println("Child>>i Value = "+i);
        }
    }

output:

parent>> i ValueTwo=
Child>>i Value = 0

2.If you create the parent class object at that time the print() method in parent class is called. Please refer the following example.

public class Test
    {
        public static void main(String[] args) 
        {
            //create the object of Parent class
            Parent parent = new Parent();
        }
    }

    class Parent
    {   
        void print()
        {
            System.out.println("parent>> i ValueOne=");
        }

        Parent()
        {
            System.out.println("parent>> i ValueTwo=");
            print();
        }
    }    

    class Child extends Parent
    {
        int i = 45;


        void print()
        {
            System.out.println("Child>>i Value = "+i);
        }
    }

output:

parent>> i ValueTwo=
parent>> i ValueOne=

3.And i think you have already cleared why that value of i is 0 or 45.

like image 4
vijayk Avatar answered Nov 17 '22 06:11

vijayk


Because at that time of first call to print method i is not initialized to 45 so its printing 0.
call goes like this

  • child constructor (as because of constructor chaining from child to parent)
  • parent constructor
  • print method (now here i is not initialized coz child constructor is not complete yet so its printing the default value of i which is 0 )
  • now after completion of parent constructor and then child constructor i gets its value which is 45 -
  • so now it prints 45 on the next call of print method
like image 2
exexzian Avatar answered Nov 17 '22 05:11

exexzian