r/learnjava • u/Eva_addict • 3d ago
I need help understanding the use of "this" inside a constructor.
*Sorry if I ask too much here but books seem to get more confuse the more you go though them*
I am learning using Deitel's book and in chapter 8.5 they have an example of Overloaded Constructors. They use them in class called Time2:
public Time2()
{
this(0, 0, 0);
}This exaplain it below but I can't understand it. In fact, I didn't even know this could be used like that. The book never showed it this way. Here it looks more like a method call. There are 5 constructors like that and each one adding one more argument to this and it makes everything else even more confuse.
6
u/gR0z3L 2d ago
I don’t know your particular example but you can find, in java, this keyword as: “this.” or this(x,y,z) or this().
Since your example refers to a Time class maybe the next example can shed some light on it:
Strictly to your example: this(0,0,0) means - call another constructor of the same class that accepts three integers and pass three zeros to it.
Again your book might show a more different/ complex exercise but it all goes down to this:
public class Time2 {
private int hour;
private int minute;
private int second;
// This constructor calls another constructor of the
// same class, passing 0 as the value for each parameter.
public Time2() {
this(0, 0, 0);
}
// This constructor initializes the object's attributes
// with the values received as parameters.
public Time2(int hour, int minute, int second) {
this.hour = hour;
this.minute = minute;
this.second = second;
}
}
Now you have two ways of creating the Time2 object:
Time2 newTimeInstance = new Time2(); // 00:00:00
Time2 newTinmeInstanceWithSetTime = new Time2(12, 30, 5); // 12:30:05
If you don’t have a constructor taking three integers in your main class you will get a compilation error when trying to call “this(0,0,0)”
This is a bit difficult to understand but you will do it, just keep studying.
1
u/desrtfx 3d ago
Constructor overloading - multiple constructors with different parameters - goes hand in hand with constructor chaining - what you are doing here.
One constructor Time2() (no argument constructor, default constructor) calls another this(0, 0, 0).
The this here simply refers to a different constructor of the same class.
In your particular case, it calls the constructor with 3 parameters, most likely Time2(int hours, int minutes, int seconds)
1
u/Eva_addict 2d ago
But how could I know it was calling the other constructor if there is not even a name on it?
1
u/desrtfx 2d ago
That's convention in Java.
You don't need to know the name.
thisin the way used in your example, as a method call, always refers to a constructor.superalways refers to the parent constructor.
thisin an assignment, e.g.this.seconds = seconds;always refers to the current instance of the class - the object you are working with.1
u/0b0101011001001011 2d ago
super always refers to the parent constructor.
Only when called. In general it means the superclass.
1
u/CanisLupus92 2d ago
Even when not explicitly called, java implicitly calls super() at the start of your constructor (even when not explicitly declaring a parent class, because then you inherit from Object).
1
u/0b0101011001001011 2d ago
I know. That's not what I meant. The comment above says that "super" always refers to a constructor, which is false.
1
u/0b0101011001001011 2d ago
this()means you call the constructor. That's just how it is. That's what the people who made java decided.1
u/voidiciant 2d ago edited 2d ago
From the API Docs. It wouldn’t explicitly state “this constructor calls this(….)” but rather smth line “this constructor creates an object with x,y,z set to <some default value>”
It might state something like “calling this constructor is the same as calling new Time(0,0,0)”Edit: if you ask how you can know by looking at the code: people already explained this. if you see this(…) in a ctor for Foo, look for a constructor called Foo(…) in that class. This might also allow you to write constructors with limited visibility
2
u/sozesghost 3d ago
It is a constructor call, which calls another, overloaded constructor from the same class, same instance even. You use it to have some base logic (assignement or validation) in one constructor, instead of duplicating it several times. The 'super' keyword can also refer to fields or methods or constructors, but from the parent class.
-1
u/vegan_antitheist 3d ago
It works like a method call. You invoke the other constructor. Instead, you can call super(). Try a debugger to see how it works.
6
u/desrtfx 3d ago
Instead, you can call super().
That's an entirely different thing to OP's case.
super()calls the parent class constructor in an inheritance hierarchy.By using
this(0, 0, 0)OP calls an overloaded constructor in the same class with different parameters.0
u/vegan_antitheist 3d ago
You have to call some constructor using this or super. If you don't it will do it automatically if possible. The compiler inserts an implicit super() as the first statement of a constructor only if you don't explicitly call this(...) or super(...) and if the superclass has an accessible no-argument constructor.
1
•
u/AutoModerator 3d ago
Please ensure that:
Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions
You include any and all error messages in full - best also formatted as code block
You ask clear questions
You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.
If any of the above points is not met, your post can and will be removed without further warning.
Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.
Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.
Code blocks look like this:
You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.
If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.
To potential helpers
Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.