9.Where should the following statement be located in the body of a subclass constructor?
super( );
1
Expert's answer
2012-12-11T10:15:18-0500
Constructor call must be the first statement in aconstructor if you try to set up some variables and then call aconstructor. You need to construct the object first, then modify it.
WRONG publicclass Foo { int i; public Foo() { i = 2; } public Foo(int x) { // fine this(); this.i = x; } public Foo(int x, int y) { int z = x*y; this(z); // not okay } }
RIGHT publicclass Foo { int i; public Foo() { i = 2; } public Foo(int x) { this(); this.i = x; } public Foo(int x, int y) { this(x*y); // now okay } }
Comments
Leave a comment