构造函数说方法不能重复

时间:2015-10-02 18:06:21

标签: java

import java.util.Scanner;

class IronMan {
private double totalTime = 3.7;

public IronMan() {
    System.out.println("First Constructor running");
}

public IronMan() {
    System.out.println("Second Constructor running");
}

}

public class Marathon {
public static void main(String[] args) throws InterruptedException {
    IronMan person1 = new IronMan();
    Scanner scan = new Scanner(System.in);
    System.out.println(
            "A triathlon is a challenging task. This program will allow you to know which is the perfect course for you.");
    Thread.sleep(3000);
    System.out.println("What is your age?");
    int age = scan.nextInt();
    Thread.sleep(1000);
    System.out.println("What is your time for one mile, in minutes?(ex: 5.3 or 6.2");
    double time = scan.nextDouble();
    Thread.sleep(1000);
    System.out.println("How much is your budget?");
    double money = scan.nextDouble();
    System.out.println(money);
    if (money <= 100) {
        System.out.println("You can't afford entrance!");
    } else if (money > 100) {
        if (age < 10) {
            System.out.println("You don't qualify!");
        } else {
            if (time > 10) {
                System.out.println("You do not qualify");
            } else {
                System.out.println("Good! you do qualify");
                IronMan person2 = new IronMan();
            }
        }
    }

}
}

我对构造函数的概念有点新意。我试图创建构造函数IronMan;但是,Eclipse在IronMan这个词下给了我一条错误信息。它说“铁人类型中的重复方法IronMan()”。我不明白为什么它说该方法是重复的,因为它应该是一个构造函数。

2 个答案:

答案 0 :(得分:1)

您有两个具有相同签名的构造函数(两者都没有参数)。这是不允许的,因为两者之间没有任何区别。

当您编写IronMan person1 = new IronMan();时,您无法指定应该调用这两个构造函数中的哪一个,因此不允许同时使用这两个构造函数。

答案 1 :(得分:0)

构造函数允许您创建对象的实例。您可以创建ironMan IronMan ironMan = new IronMan()而不设置ironMan名称和年龄,IronMan ironMan = new IronMan("Brad")这意味着您的铁人姓名是brad。 IronMan ironMan = new IronMan("Brad", 29)表示你的铁人姓名是Brad,他的年龄是29岁。如果删除IronMan()构造函数,您将强制开发人员输入ironMan名称(带IronMan(String name))或姓名和年龄(在创建IronMan实例时使用IronMan(String name, int age))。

public class IronMan {
    private String name;
    private int age;

    public IronMan() {
    }

    public IronMan(String name) {
        this.name = name;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}