-2

Here we have created a class Demo and have two method in it m1 and m2 and calling m1 throught m2 using this keyword. My question is we are passing (Demo o) as the parameter in m1 method ,how can we pass the reference of the same class as we are in as a parameter and this keyword refers to an object how can this keyword refer to reference of a class?

Any reference material is welcome.

class Demo{

    void m1(Demo o)
    {
        System.out.println("Hello");
    }
    
    void m2()
    {
        m1(this);
    }

    public static void main(String args[])
    {
        Demo o = new Demo();
        o.m2();
    }
}
dunni
  • 43,386
  • 10
  • 104
  • 99
Clayton
  • 43
  • 3
  • Are you sure that this is Java? `this()` in Java is a reference to the default constructor of a class when it is called by another constructor. And the `.` notation with the name of a method alone is also not defined (`m2.this()` is therefore invalid in multiple aspects!) I cannot even *guess* what you want to achieve with this code – and usually I am good with that kind of guessing. – tquadrat Mar 14 '21 at 11:48
  • Really sorry i have edited the code. – Clayton Mar 14 '21 at 11:50
  • You should edit the description as well. – tquadrat Mar 14 '21 at 11:51
  • My question is how can we pass reference of a class as a parameter ? – Clayton Mar 14 '21 at 11:55
  • In that post they have created an object and then passed the reference of it but i am passing a parameter without creating an object of it. – Clayton Mar 14 '21 at 11:57
  • 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) – Max Vollmer Mar 14 '21 at 13:30

1 Answers1

1

this is the reference to the instance of the class of an instance method of a class.

m1(Demo) takes an instance (any instance) of the class Demo as its argument (to be exact, it takes a reference to any instance of that class as argument).

Any instance means that it will take also the instance it belongs to.

m2() calls m1() with the current instance, represented by the this keyword. And as you can call o.m() (calling m2() on o) it is guaranteed that this refers to an existing object …

That's it!

tquadrat
  • 3,033
  • 1
  • 16
  • 29