Java 为什么可以';难道不可以这样做吗?
它表示类A的构造函数不能应用于给定的类型。您必须在构造函数Java 为什么可以';难道不可以这样做吗?,java,Java,它表示类A的构造函数不能应用于给定的类型。您必须在构造函数B()中显式调用构造函数A(int x)。也就是说,你必须写作 class A { A(int x) { System.out.println("constructor A"); } } class B extends A { B() { System.out.println(" constructor B"); } } public class C { public static void main(Stri
B()
中显式调用构造函数A(int x)
。也就是说,你必须写作
class A {
A(int x) { System.out.println("constructor A"); } }
class B extends A {
B() { System.out.println(" constructor B"); } }
public class C {
public static void main(String args[]) { B b = new B(); } }
B类扩展了A类{
B(){
超级(>);
System.out.println(“构造器B”);
}
}
如果不添加这样的超级调用,那么java将插入
super()
用于尝试调用A()
的您。由于没有构造函数A()
您会收到一个错误,即您的构造函数无法应用于参数类型。如果您编写的是参数化的构造函数,那么在类中有一个默认构造函数总是好的
class B extends A {
B() {
super(<<< insert some int here>>>);
System.out.println(" constructor B");
}
}
如果我们没有为类a指定构造函数,则没有参数的默认构造函数将与该类关联;如果为类a指定一个或多个构造函数,则每次要从该类创建对象时都必须使用其中一个构造函数。当类B扩展类a时,然后构造函数必须通过
super()
调用父类(A)的一个构造函数,如果你没有为A指定一个构造函数,那么它被简单地称为B的构造函数,如果你明确定义了A的构造函数,那么你在创建B的构造函数时必须调用它,如下所示:
class A {
A(){System.out.println("Default A");}
A(int x) { System.out.println("constructor A"); } }
class B extends A {
B() { System.out.println(" constructor B"); } }
public class C {
public static void main(String args[]) { B b = new B(); } }
您看到的是
构造函数链接
链接中的代码片段
B() { super(0)/*this call should be if the first line, you have to pass your default args if the constructor have args*/;
System.out.println(" constructor B");
}
这并不重要,因为只有一个公共类。您需要在类a中提供一个默认构造函数,这样才能正常工作,因为java在扩展时需要隐式超级构造函数,在您的例子中,这是未定义的,或者在类B中调用超级构造函数。
If a constructor does not explicitly invoke a superclass constructor, the Java compiler
automatically inserts a call to the no-argument constructor of the superclass. If the super
class does not have a no-argument constructor, you will get a compile-time error. Object
does have such a constructor, so if Object is the only superclass, there is no problem.