Aaditya
Aaditya

Reputation: 19

Java Copy Constructor is not working as expected

I am learning Java and recently gone through Copy Constructor tutorial. I tried to write Copy Constructor code however it gives unexpected output.

Question is :

Why is the first output showing 0 and null values?

Here is the object with the Copy Constructor:

class student6 {

    int id;
    String name;
    int i;
    String n;

    student6(int a, String b) {
        id = a;
        name = b;
    }

    student6(student6 s) {
        i = s.id;
        n = s.name;
    }

    void display() {
        System.out.println(i + "..." + n);
    }

    public static void main(String args[]) {
        student6 s1 = new student6(11, "Suresh");
        student6 s2 = new student6(s1);

        s1.display();
        s2.display();
    }
}

Output

0...null

11...Suresh

Upvotes: 1

Views: 689

Answers (3)

Suresh Atta
Suresh Atta

Reputation: 121998

You have to change you copy constructor logic from

student6(student6 s)
{
i=s.id;
n=s.name;
}

to

student6(student6 s)
 {
    id=s.id;
    name=s.name;
 }

In your display method you are printing id and name. So you have to initialize them only to see the result.

And please follow Java naming conventions. Class names starts with Capital letter. student6 should be Student6

P.S : Thanks for printing my name ;)

Upvotes: 5

Luigi Cortese
Luigi Cortese

Reputation: 11131

s1 only initialize int id; and String name;: this line

student6 s1 = new student6(11, "Suresh");

calls the first constructor

student6(int a, String b) {
    id = a;
    name = b;
}

So, calling

System.out.println(i + "..." + n);

will print default values for i and n

Upvotes: 2

Blake Yarbrough
Blake Yarbrough

Reputation: 2316

In the first constructor you are setting the fields id and name and the second constructor sets the fields i and n.

When you print both times you print the values of i and n which are not set for the first object, so they are 0 and null respectively.

Here is a modification that results in the output I believe you are expecting.

class student6 {

    int id;
    String name;

    student6(int a, String b) {
        id = a;
        name = b;
    }

    student6(student6 s) {
        id = s.id;
        name = s.name;
    }

    void display() {
        System.out.println(id + "..." + name);
    }

    public static void main(String args[]) {
        student6 s1 = new student6(11, "Suresh");
        student6 s2 = new student6(s1);

        s1.display();
        s2.display();
    }
}

Upvotes: 1

Related Questions