I ran into this block of code, and there is this one line I don't quit understand the meaning or what it is doing.
public Digraph(In in) { this(in.readInt()); int E = in.readInt(); for (int i = 0; i < E; i++) { int v = in.readInt(); int w = in.readInt(); addEdge(v, w); } }
I understand what this.method()
or this.variable
are, but what is this()
?
The this keyword refers to the current object in a method or constructor. The most common use of the this keyword is to eliminate the confusion between class attributes and parameters with the same name (because a class attribute is shadowed by a method or constructor parameter).
The "this" keyword in Java is used as a reference to the current object, within an instance method or a constructor. Yes, you can call methods using it.
It means "call constructor which is without arguments". Example: public class X { public X() { // Something. } public X(int a) { this(); // X() will be called. // Something other. } }
A method is a block of code which only runs when it is called. You can pass data, known as parameters, into a method. Methods are used to perform certain actions, and they are also known as functions. Why use methods?
This is constructor overloading:
public class Diagraph { public Diagraph(int n) { // Constructor code } public Digraph(In in) { this(in.readInt()); // Calls the constructor above. int E = in.readInt(); for (int i = 0; i < E; i++) { int v = in.readInt(); int w = in.readInt(); addEdge(v, w); } } }
You can tell this code is a constructor and not a method by the lack of a return type. This is pretty similar to calling super()
in the first line of the constructor in order to initialize the extended class. You should call this()
(or any other overloading of this()
) in the first line of your constructor and thus avoid constructor code duplications.
You can also have a look at this post: Constructor overloading in Java - best practice
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With