子类构造函数隐式调用默认构造函数

时间:2014-02-28 16:36:16

标签: java constructor

当我尝试创建一个B类型的对象时,下面的代码给出了一个错误。我的问题是为什么不是A的默认构造函数?

class A
{
  private int a;

  A(int a)
  {
    this.a = a;
    System.out.println("This is constructor of class A");
  }
} 

class B extends A
{
  private int b;
  private double c;

  B(int b, double c)
  {
    this.b = b;
    this.c = c;
    System.out.println("This is constructor of class B");
  } 
} 

6 个答案:

答案 0 :(得分:2)

  

我的问题是为什么不是A的默认构造函数?

因为没有一个。当您提供自己的参数化构造函数时,编译器将不会添加默认构造函数。所以,你似乎在想的类A有一个0-arg构造函数,没有。你必须明确添加一个。

答案 1 :(得分:0)

A的默认构造函数意味着新的A()。您没有可用的构造函数,这意味着构造A的唯一方法是调用新的A(int)。由于没有默认构造函数,B必须显式调用A的超级构造函数才能正确初始化A.

答案 2 :(得分:0)

因为,只有在Java中没有构造函数时才会调用默认构造函数。

答案 3 :(得分:0)

当您定义自己的构造函数时,java编译器不再自动插入默认构造函数。

在构造B的代码中,第一行上有一个隐式调用给超类构造器。 super();虽然,因为你已经覆盖了A的默认构造函数,所以没有构造函数调用可以工作,因为编译器不会自动使用必要的参数调用超类构造函数。您应该在B构造函数的第一行添加一行,以使用它需要的int参数调用A的超类构造函数,或者为A定义一个类似于不带参数的默认构造函数的构造函数。

您可以重载构造函数,以便一个构造函数像默认构造函数一样无参数,然后使用其他构造函数来获取参数。 :d

根据您的代码

,示例如下
class A
{
 private int a;

 A( int a)
 {
  this.a =a;
  System.out.println("This is constructor of class A");
}

//overload constructor with parameterless constructor similar to default 
A() { 
   System.out.println("this is like a default no-args constructor");
}
 } // end class A

class B extends A
{
 private int b;
 private double c;

   // add in another constructor for B that callers can use
   B() { 
      int b = 9;
      System.out.println("new B made in parameterless constructor");

   }

   B(int b,double c)
   {
     super(b); // this calls class A's constructor that takes an int argument :D
     this.b=b;
     this.c=c;
      System.out.println("This is constructor of class B");
  } 
}  // end class B

答案 4 :(得分:0)

尝试添加引用超类构造函数的扩展类构造函数,即

class B extends A
{
private int b;
private double c;
B(int b,double c, int superVal)
{
super(superVal);
this.b=b;
this.c=c;
System.out.println("This is constructor of class B");
} 
} 

答案 5 :(得分:0)

默认构造函数是一个不包含任何参数的构造函数。如果没有这样的默认构造函数,编译器会创建一个,只要不存在任何其他参数化构造函数。

在此示例中,由于存在可用的参数化构造函数,因此编译器不会创建默认构造函数。由于没有可用的默认/无参数构造函数,因此会导致编译错误

相关问题