简体   繁体   中英

Why do i get a error when i try to define these three constructors? Examples given

Okay so the problem is, NetBeans is saying the second one is already defined. These three are my constructors at the top, The whole program is listed in case a set or get method is the error of it. So to be clear i am talking about

public Dog(String initialName) public Dog(String initialBreed) public Dog(double initialWeight)

The error shows up on public Dog(String initialBreed). Did i misuse the Overload method? Also i must use the overload method it is mandatory.

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;
}

}

The problem is that two of your constructors take the same argument:

public Dog(String initialName)

public Dog(String initialBreed){

They both take string . You can't have two methods with the exact same name and parameters.

Based on what I think you are trying to do, you might want a single constructor that takes all 3 of those parameters:

public Dog(String initialName, String initialBreed, double initialWeight){
public Dog(String initialName)
{
name = initialName;
breed = "no breed";
weight = 0.0;
}

public Dog(String initialBreed){
name = "no name";
breed = initialBreed;
weight = 0.0;
}

The above two constructor which you defined are not overloaded properly as both are having same header with same type and numbers of arguments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM