Sundyp Krishna
Sundyp Krishna

Reputation: 61

What's the difference between these two constructors in java ? (Memory)

here in this code

public class Base {
    int length, breadth, height;

    Base(int l, int b, int h) {
        length = l;
        breadth = b;
        height = h;
    }
}

and

Base(int l, int b, int h) {
    this.length = l;
    this.breadth = b;
    this.height = h;
}

here what's the difference between this two constructors intialization? which method is highly preferred? how it varies in terms of memory allocation?

Upvotes: 0

Views: 185

Answers (4)

Jakub H
Jakub H

Reputation: 2158

There is no difference, because this is implicitly added to the first constructor. In Java in terms of construtors there is a convention to use the second approach, because it's more readable and not as error prone as the first approach.

There is also no difference in memory allocation, because the byte code it exactly the same.

Upvotes: 0

Ankur Shanbhag
Ankur Shanbhag

Reputation: 7804

Both are same. In the first case, compiler will implicitly add this keyword while compiling it.

The only difference is that seconds seems more readable. It easily differentiates member variables from local ones. Generally this comes in handy to refer member variables when local variables shadow them.

Upvotes: 0

deviantfan
deviantfan

Reputation: 11414

They are the same.
A difference would be if you write this:

Base(int length, int breadth, int height)
{
   this.length=length;
   this.breadth=breadth;
   this.height=height;
}

because there are two variables named length etc.

Upvotes: 0

m0skit0
m0skit0

Reputation: 25863

There's no difference. In the first constructor you just omit this while in the second you explicitly specify it. Generated bytecode is exactly the same (you can check it). It's just a matter of style if you want to put this or not, unless the field has the same name as the parameter, in which case this is mandatory to avoid ambiguity, for example:

Base(int length,int breadth,int height) {
   this.length = length;
   this.breadth = breadth;
   this.height = height;
}

(Please use spaces wisely, it makes your code more readable).

Upvotes: 8

Related Questions