好的,问题是,NetBeans 说第二个已经定义了。这三个是我在顶部的构造函数,列出了整个程序以防 set 或 get 方法是它的错误。所以要明确我在谈论
公共(public)狗(字符串初始名称) 公共(public)狗(字符串初始品种) public Dog(double initialWeight)
错误出现在 public Dog(String initialBreed) 上。我是否滥用了 Overload 方法?我还必须使用强制性的重载方法。
package dog;
import java.util.*;
public class Dog
{
// instance variables
private String name;
private String breed;
private double weight;
public Dog( )
{
name = "no name";
breed = "no breed";
weight = 0.0;
}
public Dog(String initialName)
{
name = initialName;
breed = "no breed";
weight = 0.0;
}
public Dog(String initialBreed){
name = "no name";
breed = initialBreed;
weight = 0.0;
}
public Dog(double initialWeight){
name = "no name";
breed = "no breed";
weight = initialWeight;
}
public void SetDog(String newName, String newBreed, double newWeight)
{
name = newName;
breed = newBreed;
if (newWeight <= 0)
System.out.println("Error: Negative weight.");
else
weight = newWeight;
}
public void setName(String newName){
name = newName;
}
public void setBreed(String newBreed){
breed = newBreed;
}
public void setWeight(double newWeight){
weight = newWeight;
}
public double getWeight(){
return weight;
}
public String getName(){
return name;
}
public String getBreed(){
return breed;
}
最佳答案
问题是你的两个构造函数采用相同的参数:
public Dog(String initialName)
public Dog(String initialBreed){
它们都采用string
。不能有两个名称和参数完全相同的方法。
根据我认为您正在尝试做的事情,您可能需要一个包含所有 3 个参数的构造函数:
public Dog(String initialName, String initialBreed, double initialWeight){
关于java - 为什么我尝试定义这三个构造函数时会出错?给出的例子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7801181/