0
‘This’ Keyword usage
class S2{ void m(S2 obj){ System.out.println("Hello"); } void p(){ m(this); } public static void main(String args[]){ S2 s1 = new S2(); s1.p(); } }// output: Hello class A{ A get(){return this;} } class B1 extends A{ B1 get(){return this;} void message(){System.out.println("welcome to covariant return type");} public static void main(String args[]){ new B1().get().message(); } } // output: welcome to covariant return type Iam not understanding the purpose of ‘this’ keyword in both programs. Is This keyword is used to call class or obj? Can anyone plz explain
2 Respuestas
+ 1
"This" is used as a reference of an object who uses a method or a variable.
For example the first program the m function needs an object of the class S2, when you call the function p it calls the function m and pass "this" as parameter, referring to the object who activate it.
This is more visible if you print in console a variable of the object instead a constant message.
Have a nice day 🧏🏼♀️🧏🏼♀️🧏🏼♀️
0
//interesting Sololearn runs both main() methods in one code :)
modify your code for print object and this object:
class S2 {
void m(S2 obj) {
System.out.println(obj+" this obj");
}
..
..main(..) {
S2 s1 = new S2();
System.out.println(s1 +" s1");
s1.p();
class B1 ..
..main(..)
B1 b1 = new B1();
System.out.println(b1 +" b1");
System.out.println(b1.get()+" this obj of B1" );