0

Caller.java

ListNode n = new ListNode(5);

ListNode.java

class ListNode{
  int val;
  ListNode next;
   public ListNode(int x){
     val = x;
   }

//METHOD

 public void print(){
    this.node = node;
     //other
  }
}

For every time I do something like

ListNode n = new ListNode(5);
n.print();

The print method inside ListNode.java has a this, which only refers to that new instance? (n in this case)

2 Answers2

0

The word this refers to the actual instance. In this case this refers to n reference. You have an auto relationship in your class. So, maybe you have misspelled this.node = node instead of this.next = node or something like that. In this case, each instance (n and next inside n) have its own scopes represented by this keyword inside a class.

Anderson Marques
  • 808
  • 8
  • 13
0

Yes that is correct.

Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.

https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html

hubpixel
  • 319
  • 1
  • 10