【问题标题】:Superclass's default no argument constructor [duplicate]超类的默认无参数构造函数[重复]
【发布时间】:2013-06-13 16:36:19
【问题描述】:

在java教程中,

http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html

您不必为您的类提供任何构造函数,但这样做时必须小心。编译器会自动为任何没有构造函数的类提供无参数的默认构造函数。此默认构造函数将调用超类的无参数构造函数。在这种情况下,如果超类没有无参数构造函数,编译器会报错,因此您必须验证它是否存在。如果你的类没有显式的超类,那么它有一个隐式的 Object 超类,它确实有一个无参数的构造函数。

谁能给我一个例子,这个编译错误可能在哪里?

【问题讨论】:

  • 今天早些时候不是有人问过这个问题吗?
  • 这个问题已经被问过很多次了,答案都是一样的。例如:stackoverflow.com/questions/5286348/…。我的建议,请在发布问题之前进行快速谷歌搜索。您可以在这里更快地获得大量答案并减少欺骗。
  • @Sebastian:是的,有人在 4 小时前被询问并删除了。 - stackoverflow.com/questions/17087267/…

标签: java inheritance constructor


【解决方案1】:
class A
{
    int a;
    A(int a)
    {
        this.a=a;
    }
}

class B extends A
{
    B(int a)
    {
        this.a=a;
    }
}

class C 
{
    public static void main(String args[])
    {
        B obj=new B(20);
        System.out.println("a = "+obj.a);
    }
}


Error:Constructor A in class A cannot be applied to given types;
{
^
required: int
found:no arguments
reason: actual and formal argument lists differ in length

【讨论】:

    【解决方案2】:
    class A
    {
        public A(int n)
        {
    
        }
    }
    
    class B extends A
    {
    
    }
    

    【讨论】:

    • 是的,所以我是人类! :)
    【解决方案3】:

    假设你有一个Super 类

    class Super {
    
     // no constructor
     // Java compiler will assign a default constructor
     // Super () {} 
    
    }
    

    还有一个Child 类

    class Child extends Super {
    
          public Child() {
              //super(); --> this statement will be inserted by default by Java compiler, even though you don't put it in your code
          }
    
    }
    

    如果Super是这样的

    class Super {
    
      Super(int a) {
        // Now this is the only constructor Super class has
        // Java doesn't insert a default constructor now..
      }
    
    }
    

    Child 不能没有参数构造函数,因为Super 没有它了

    class `Child` {
    
      Child() {
         // super();
         //this will be error since there is no "no-argument" constructor in Super
      }
    
    }
    

    【讨论】:

    • 有一种情况,然而,Child 类在这种情况下可以有一个默认构造函数。这是当无参数构造函数使用参数调用 super() 时,例如super(0) 或 super(5).
    猜你喜欢
    • 1970-01-01
    • 2012-04-24
    • 2020-09-04
    • 2019-11-29
    • 1970-01-01
    • 2016-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多