java - 无法创建构造函数

标签 java object constructor instance

class Human{

    // declared instance variables 
    String name;
    int age;

    // instance method
    void speak(){
        System.out.println("My name is: " + name);
    }

    int calculateYearsToRetirement(){
        int yearsLeft = 65 - age;
        return yearsLeft;
    }

    int getAge(){
        return age;
    }

    String getName(){
        return name;
    }

    // so when I create an instance, i can't have constructor?
    // error here
    Human(int age){
        age = this.age;
    }
}



}
public class GettersAndReturnValue {

    public static void main(String[] args) {
        // error here because I created a constructor Human(int a)
        Human human1 = new Human();
        human1.name = "Joe";
        human1.age = 25;

        human1.speak();
        int years = human1.calculateYearsToRetirement();

        System.out.println("Years till retirements " + years);

        int age = human1.getAge();
        System.out.println(age);
    }

}

我尝试创建一个构造函数 Human(int Age) 来练习“this”关键字并将年龄从 25 更改为其他值,但我收到错误,因为我有一个 Human 类和一个 Human 构造函数。当我尝试在主方法中创建 Human Type 的实例时,Eclipse 要求我删除构造函数

最佳答案

您交换了作业中的顺序,

Human(int age){
    age = this.age;
}

应该类似于(也不要忘记初始化name)

Human(int age){
    this.age = age;
    this.name = "Unknown";
}

您正在为传入的参数分配默认值0。如果您提供构造函数,那么编译器将不再插入默认构造函数,

Human() {
    this.age = 0;
    this.name = "Unknown";
}

您也可以添加一个采用该名称的构造函数,

Human(int age, String name) {
    this.age = age;
    this.name = name;
}

然后你可以像这样调用它(在main中)

Human human1 = new Human(25, "Joe");
// human1.name = "Joe";
// human1.age = 25;

关于java - 无法创建构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30147742/

相关文章:

java - 如何在 Android 中以编程方式打开设置中的 'App Permissions' 页面?

java - 在运行时使用 java 中的类名创建对象数组

c++ - C++ 构造函数中的混淆

c++ - 何时对多参数构造函数使用显式说明符?

Java 需要有关构造函数的帮助

java - Lucene RAMDirectory 已弃用 - 无论如何如何仅保留目录 RAM?

java - checkstyle 中方法局部常量的命名

Java:FilterInputStream相比其他流有什么优势和用途

JavaScript 访问父对象属性

javascript - 在 jQuery 中解析 JSON 对象