0

why its is showing the output of last method call i.e "CopyConstructors c3=new CopyConstructors(c2)" = 0?

public class CopyConstructors { private int l,b,h; public CopyConstructors() { l=b=h=0; System.out.println("l="+l+" b="+b+" h="+h); } public CopyConstructors(int i) { l=b=h=i; System.out.println("l="+l+" b="+b+" h="+h); } public CopyConstructors(int l,int b,int h) { l=l;b=b;h=h; System.out.println("l="+l+" b="+b+" h="+h); } public CopyConstructors(CopyConstructors c) { l=c.l; b=c.b; h=c.h; System.out.println("l="+l+" b="+b+" h="+h); } } class UseCopyConstructors { public static void main(String[] args) { CopyConstructors c=new CopyConstructors(); CopyConstructors c1=new CopyConstructors(5); CopyConstructors c2=new CopyConstructors(1,2,3); CopyConstructors c3=new CopyConstructors(c2); //output: l=0 b=0 h=0 l=5 b=5 h=5 l=1 b=2 h=3 l=0 b=0 h=0 >>>why it is not showing (1,2,3)? } }

15th Oct 2020, 9:44 AM
Harsh Vyas
Harsh Vyas - avatar
3 ответов
+ 1
You have not used the 'this' keyword which is specific to objects. So the value returned is the default value of each variable which is 0. This will work. class CopyConstructors { private int l,b,h; public CopyConstructors() { this.l=this.b=this.h=0; System.out.println("l="+l+" b="+b+" h="+h); } public CopyConstructors(int i) { this.l=this.b=this.h=i; System.out.println("l="+l+" b="+b+" h="+h); } public CopyConstructors(int l,int b,int h) { this.l=l; this.b=b; this.h=h; System.out.println("l="+l+" b="+b+" h="+h); } public CopyConstructors(CopyConstructors c) { l=c.l; b=c.b; h=c.h; System.out.println("l="+l+" b="+b+" h="+h); } }
15th Oct 2020, 10:15 AM
Avinesh
Avinesh - avatar
+ 1
Harsh Vyas you're welcome.
15th Oct 2020, 11:19 AM
Avinesh
Avinesh - avatar
0
Thanks man 👍👍 avinesh
15th Oct 2020, 11:18 AM
Harsh Vyas
Harsh Vyas - avatar