Xah Lee, 2005-02, 2007-12
One of following 3 codes won't compile. See if you can guess which, and fix it. (answer follows.)
✻ ✻ ✻
class B { int x; void B (int n) {x=n;}} public class x1 { public static void main(String[] args) {B b = new B(0);}}
✻ ✻ ✻
class B { int x; void B (int n) {x=n;}} public class x2 { public static void main(String[] args) {B b = new B();}}
✻ ✻ ✻
class B { int x; void B () {x=0;}} public class x3 { public static void main(String[] args) {B b = new B();}}
Answer: The x1 does not compile. The java version used is:
java version "1.5.0_13" Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_13-b05-241) Java HotSpot(TM) Client VM (build 1.5.0_13-121, mixed mode, sharing)
Here's why.
Constructor are distinguished from methods by the absence of the return type declaration, not by the class's name. So, in a code like this:
class B { int x; void B (int n) {x=n;}} public class x2 { public static void main(String[] args) {B b = new B();}}
Java doesn't see any user defined constructor. The void B … is taken as a method because of the existence of the return type. The code compiles fine. With the call new B(), Java simply calls a default constructor it created internally, which does nothing.
Similarly, in this case:
class B { int x; void B (int n) {x=n;}} public class x1 { public static void main(String[] args) {B b = new B(0);}}
Java doesn't see any user defined constructor. To the compiler, the B class has a user defined method of the same name. Java also defined a default constructor for class B that takes no argument. So, the call new B(0) is a compilation error since there is no constructor that takes a argument.
In summary, remember to not give a return type when defining a constructor.
Thanks to Russell Miles and others on the Apple's Java forum for help.
blog comments powered by Disqus