Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "this()" method mean?

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()?

like image 993
Sugihara Avatar asked Apr 07 '13 20:04

Sugihara


People also ask

What is this () method?

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).

Can we use this () in a method?

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.

What is the meaning of () in Java?

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. } }

What is the use of method?

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?


1 Answers

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

like image 77
Avi Avatar answered Oct 02 '22 05:10

Avi