private constructor is invisible to the sub-classes. This might cause a compiling error, "no suitable constructor found" as defining a subclass, especially as a non-arg user-defined constructor has been explicitly defined.
Here is a case: Line //1 generates a compiling error.
Reasons:
1) as having no any user-defined constructor, Java will automatically add a default constructor.
2) a default constructor is non-arg constructor, in which super() will be added in the first line; and instance variable will be init. immediately following.
/** * * @author YNZ */ class A { int a; int b; //invisible to subclass private A() { } public A(int a, int b) { this.a = a; this.b = b; } protected A(float a, int b) { this.a = (int) a; this.b = b; } } class B extends A { //1 }
how about removing it?
class A { int a; int b; public A(int a, int b) { this.a = a; this.b = b; } protected A(float a, int b) { this.a = (int) a; this.b = b; } } class B extends A { //1 }
this will still cause the same compiling error. since there is only argument constructors have been defined, the sub-class will think, non-argument constructor has no been defined.
How about removing all constructors from A? it should be correct. As compiling time, a default non-arg constructor will be added by Java with in the A; and a default non-argument constructor will be added by Java with in the B, in which a super() being invoked from the A.
So the following should be correct.
class A { int a; int b; } class B extends A { //1 }
No comments:
Post a Comment