0

Can anyone explain the output and the function of this keyword in these two programs

public class Sample { int ivalue; double dvalue=1.7; Sample(int ivalue,double dvalue ) { System.out.println(ivalue+dvalue); System.out.println(this.ivalue+this.dvalue); } public static void main(String[] args) { Sample ref=new Sample(25,3.19); System.out.println(ref.ivalue); System.out.println(ref.dvalue); Sample ref1 =new Sample(19,9.1); System.out.println(ref.ivalue); System.out.println(ref.dvalue); } } Scenario2 public class Sample { int ivalue; double dvalue=1.7; Sample(int ivalue,double dvalue ) { System.out.println(ivalue+""+this.devalue); System.out.println(ivalue+""+this.dvalue); this.ivalue=ivalue; this.dvalue=dvalue; } public static void main(String[] args) { Sample ref=new Sample(25,3.19); System.out.println(ref.ivalue+" "+ref.dvalue); Sample ref1 =new Sample(19,9.1); System.out.println(ref.ivalue); System.out.println(ref.dvalue); } }

12th Dec 2019, 1:57 AM
Ajoh Pv
Ajoh Pv - avatar
1 ответ
0
It's pretty simple, the this keyword is used to point the current object. Constructor is nothing but a method which accepts parameters like any other method. What you do inside it is all that matters. So in 1st case- 25, 3.19 is passed to the constructor so the first line prints the sum of those values which is 28.19 The second line will print 1.7 because when you create an object of the class, it is initialized with the values of instance variables. So if you want to change them and print a different answer then you can do that in the main method by doing- ref.ivalue = new_value; ref.dvalue = new_value; OR inside the constructor do- this.ivalue = ivalue; this.dvalue = dvalue; Explaining every output line by line will take a lot of time. Kindly try to proceed with this knowledge and try to predict the answers for the rest. Edit: Hope you know that instance variables if not initialized will have default values.
12th Dec 2019, 10:55 AM
Avinesh
Avinesh - avatar