Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusion in Constructor Overloading Example

Tags:

java

The following program gives output as

 I am Parameterized Ctor
 a = 0
 b = 0

public class ParameterizedCtor {

    private int a;
    private int b;

    public ParameterizedCtor() {
        System.out.println("I am default Ctor");
        a =1;
        b =1;
    }

    public ParameterizedCtor(int a, int b) {
        System.out.println(" I am Parameterized Ctor");
        a=a;
        b=b;

    }
    public void print() {
        System.out.println(" a = "+a);
        System.out.println(" b = "+b);
    }

    public static void main(String[] args) {

        ParameterizedCtor c = new ParameterizedCtor(3, 1);
        c.print();
    }

}

What is the reason?

like image 627
Abi Avatar asked Jan 10 '11 11:01

Abi


3 Answers

this is called variable shadowing and default value of int is 0

make it like

 public ParameterizedCtor(int a, int b) {
        System.out.println(" I am Parameterized Ctor");
        this.a=a;
        this.b=b;
 }  

Also See

  • Something about this
like image 30
jmj Avatar answered Sep 22 '22 07:09

jmj


The un-initialized private variables a and b are set to zero by default. And the overloading c'tctor comes into place.ie, parameterCtor(int a, int b) will be called from main and the local variables a & b are set to 3 and 1, but the class variables a and b are still zero. Hence, a=0, b=0 (default c'tor will not be called).

To set the class variable, use:

this.a = a;
this.b = b;
like image 106
aTJ Avatar answered Sep 21 '22 07:09

aTJ


You need to do this:

public ParameterizedCtor(int a, int b) {
    System.out.println(" I am Parameterized Ctor");
    this.a=a;
    this.b=b;
}

otherwise, you're just re-assigning the a and b parameters to themselves.

like image 34
skaffman Avatar answered Sep 22 '22 07:09

skaffman