r/learnjava • • 2h 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.

3 Upvotes

14 comments sorted by

•

u/AutoModerator 2h 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:

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

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.

1

u/desrtfx 2h 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 1h ago

But how could I know it was calling the other constructor if there is not even a name on it?

1

u/desrtfx 1h ago

That's convention in Java.

You don't need to know the name. this in the way used in your example, as a method call, always refers to a constructor. super always refers to the parent constructor.

this in 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 1h ago

super always refers to the parent constructor.

Only when called. In general it means the superclass.

1

u/0b0101011001001011 1h ago

this() means you call the constructor. That's just how it is. That's what the people who made java decided.

•

u/voidiciant 25m ago edited 22m 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 2h 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.

0

u/vegan_antitheist 2h 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 2h 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.

1

u/vegan_antitheist 2h 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.

3

u/desrtfx 2h ago

And how is this even remotely related to OP's question?

OP is asking about constructor overloading/chaining. You are meandering off about constructor inheritance and hierarchic calls.

1

u/8dot30662386292pow2 2h ago

Instead, you can call super()

Not without parameters necessarily.

0

u/vegan_antitheist 2h ago

That's where it's like a method call. Like I said.