Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/367.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 子类构造函数对默认构造函数的隐式调用_Java_Constructor - Fatal编程技术网

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

Java 子类构造函数对默认构造函数的隐式调用,java,constructor,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

当我尝试创建类型为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");
  } 
} 
我的问题是,为什么不调用的默认构造函数


因为没有。当您提供自己的参数化构造函数时,编译器不会添加默认构造函数。因此,类
A
,您似乎认为它有一个0-arg构造函数,但它没有任何构造函数。必须显式添加一个。

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

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

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

在构造B的代码中,在第一行有一个对超级类构造函数的隐式调用<代码>超级()虽然,由于您已重写了的默认构造函数,但由于编译器不会使用必要的参数自动调用超类构造函数,因此没有可以使用的构造函数调用。您应该在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

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

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");
} 
} 

默认构造函数是不包含任何参数的构造函数。如果没有此类默认构造函数,编译器将创建一个,前提是没有任何其他可用的参数化构造函数


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

这是基本的Java 101,在这里发布之前,您应该努力使用教程和其他资源来研究它。请阅读和以了解StackOverflow的目的和范围。提示:它的目的是作为解决实际问题的长期资源,而不是获得基本的教程指导。关于SO的问题和答案旨在对未来的搜索者有用,因此复制此类信息没有什么长期价值。您能否解释一下,如果我编写
b1=new B(10,8.6),为什么会产生错误?这是因为编译器试图查找
A()
构造函数,但超类中没有构造函数。