1 You cannot invoke constructors directly except from within other constructors.
2 Constructors invoking each other - by either super( ) or this(...) - must be the first statement in the constructor code body. Explicitly calling super( ) is entirely optional. The JVM will do it anyway.
3 You will not get a parameter-less default constructor automatically created for you if you create another constructor with parameters. Doing so gives a compile error if anyone invokes the (now-nonexistant) default constructor via a new. i.e.
class Test {
public Test(int i ) { }
}
class Two extends Test { // simply extending Test will trigger the error
public static void main(String[] args) {
Test T = new Test( ); } // any explicit new will trigger the error
}
4 You cannot return any values from a constructor. Adding a return type to what looks like a constructor just makes it a legal method. i.e.
class Test {
int i;
public int Test( return i; ) { } // Test is now just another legal method
}
class Two extends Test {
public static void main(String[] args) {
Test T = new Test( ); }
}
5 You cannot mark constructors void or static. They can only be public, private, or protected.
6 You cannot invoke your own same constructor again, from within the constructor, or the compiler detects a circular reference. i.e.
this( yoursameparmshere ); won't work inside the same constructor.
You can call another constructor using this with this(differentparms);
2 Constructors invoking each other - by either super( ) or this(...) - must be the first statement in the constructor code body. Explicitly calling super( ) is entirely optional. The JVM will do it anyway.
3 You will not get a parameter-less default constructor automatically created for you if you create another constructor with parameters. Doing so gives a compile error if anyone invokes the (now-nonexistant) default constructor via a new. i.e.
class Test {
public Test(int i ) { }
}
class Two extends Test { // simply extending Test will trigger the error
public static void main(String[] args) {
Test T = new Test( ); } // any explicit new will trigger the error
}
4 You cannot return any values from a constructor. Adding a return type to what looks like a constructor just makes it a legal method. i.e.
class Test {
int i;
public int Test( return i; ) { } // Test is now just another legal method
}
class Two extends Test {
public static void main(String[] args) {
Test T = new Test( ); }
}
5 You cannot mark constructors void or static. They can only be public, private, or protected.
6 You cannot invoke your own same constructor again, from within the constructor, or the compiler detects a circular reference. i.e.
this( yoursameparmshere ); won't work inside the same constructor.
You can call another constructor using this with this(differentparms);
No comments:
Post a Comment