0

I'm not entirely sure how to word the question properly in google without returning this.instanceVar, so any and all help is sincerely appreciated.

public class PracticeThis {
    private String str;

    public PracticeThis(){

        //What is "this" referring/doing??

        this("pizza Rulez");

    }

    public PracticeThis(String str){
        this.str = str;
    }

    public void practiceMyThisKnowledge(){
        String str = "Who says pizza rulez?";

        System.out.println(str);
       
        //Not sure how "this" is interacting here;
        System.out.println(this);
    }

    @Override
    public String toString(){
    return "According to practiceThis: " + str;
   }
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • Does this answer your question? [What is the meaning of "this" in Java?](https://stackoverflow.com/questions/3728062/what-is-the-meaning-of-this-in-java) – Thomas Kläger Jun 21 '22 at 04:50

1 Answers1

-2

In this("pizza Rulez");, this(String) refers to the constructor with one string parameter of this class.

In System.out.println(this);, this refers to an instance of the PracticeThis class.

If you try to print the PracticeThis class, java will call the methods toString() in the class.

Zhoumin Lu
  • 42
  • 5
  • Not here it doesn't. It refers to another constructor. – user207421 Jun 21 '22 at 05:00
  • this() vs this are different stuffs. Here this() constructor is being called to call the overloaded constructor. The this keyword is normally used to make reference to the current instance of a class(the object) – Pawan.Java Jun 21 '22 at 05:02