Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

wrong output?

 
pras
Ranch Hand
Posts: 188
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class Test7{
public Test7(){}
public Test7(Test7 ref){
this (ref,"Hai");
}
public Test7(Test7 ref,String str){ /***what i thought as a problem***/
ref.Test7(str);
System.out.println("Hi");
}
public void Test7(String str){
System.out.println(str);
}
public static void main(String[] args){
Test7 t = new Test7();
Test7 t7 = new Test7(t);
}
}



/**************question***********/
the output i get is Hai Hi
but according to what i understand it should be a compiler error because there is a constructer which takes two arguments. but there are none passed from main*********/ /**** can anyone help with "this" keyword iknow it refers to the current object**** i need a bit more explanation with example*** like when it is passed as a parameter what is happening******/
 
Maurizio Nagni
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you can have two "kinds" of this

The first is the typical this. This is the reference to the instance.
for example in this case you assign a value (test) to an parameter (this.test) of the instance of the class.

The second is this(par1, par2, ....). In this case you are NOT referring to an class instance because the class is still not instantiated but you are requiring a specific constructor of that class.

and it is in the second meaning that you are using the this when you write ; when you have realize this fact you can follow the constructors and understand the reason of your output: you are instantiating two object but only the second (t7) is the reason of the output.

Ciao
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic