java - 未定义的构造函数(java)

标签 java inheritance methods constructor

所以我有一个名为 User 的 java 类,它包含这样的构造函数:

public class User extends Visitor {
    public User(String UName, String Ufname){
        setName(UName);
        setFname(Ufname);
    }
}

然后他的问题出现在我的另一个名为 Admin 的类中:

public class Admin extends User {  //error "Implicit super constructor User() is undefined for default constructor. Must define an explicit constructor"

//public Admin() { } //tried to add empty constructor but error stays there

    //}


    public void manage_items() {            

        throw new UnsupportedOperationException();
    }

    public void manage_users() {   

        throw new UnsupportedOperationException();
    }
}

我收到错误默认构造函数的隐式 super 构造函数 User() 未定义。必须在代码中标记的地方定义一个显式构造函数。我不知道如何解决这个问题,而且我对java真的很陌生。

最佳答案

如果您没有向类添加构造函数,系统会自动为您添加一个构造函数。对于 Admin 类,它看起来像这样:

public Admin() { 
    super();
}

调用 super() 正在调用父 User 类中的以下构造函数:

public User() {
    super();
}

由于此构造函数不存在,您将收到错误消息。

有关默认构造函数的更多信息,请参见此处: http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html

You don't have to provide any constructors for your class, but you must be careful when doing this. The compiler automatically provides a no-argument, default constructor for any class without constructors. This default constructor will call the no-argument constructor of the superclass. In this situation, the compiler will complain if the superclass doesn't have a no-argument constructor so you must verify that it does. If your class has no explicit superclass, then it has an implicit superclass of Object, which does have a no-argument constructor.*

关于java - 未定义的构造函数(java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58912854/

相关文章:

c++ - 派生自并合成相同的类。 C++

ruby - 在 Ruby 中调用 super 方法

java - Readlock和Writelock会导致writer饿死吗?

java - Apache POI 无法检测哈希格式的数字

apache - 如何阻止子目录继承父级的 htaccess 规则

javascript - 如果变量是父类(super class)类型, typescript 不允许子类方法

php - 在 Eloquent 查询中使用 Laravel 模型方法

python - 如何检查Python中是否存在方法?

java - Docker 将应用程序(服务)日志存储在文件夹中并及时清除它们

java - 如何向 Spring 提供运行时特定的配置元数据?