【问题标题】:I need to create two more constructors, but Java won't let me我需要再创建两个构造函数,但 Java 不允许我这样做
【发布时间】:2012-09-25 14:47:30
【问题描述】:

好的,我需要创建三个构造函数作为项目的一部分,一个默认,一个通用和一个副本。我设法创建了一个默认构造函数,但我无法创建通用构造函数或复制构造函数,否则我的代码将无法编译。如果有人知道答案,这是代码:

package lab02;

import javax.swing.JOptionPane;

/**
 * Stores the personal details of a friend.
 * 
 * @author Keith Francis(11109971)
 * @date 4-10-2012
 */
public class Friend {

    private String firstName;// stores first name
    private String surname;// stores surname
    private String address;// stores address
    private int age;// stores age in years
    private int height;// stores height in cms
    private String hairColourString;// stores hiar colour as a string

    private boolean colourTrue = false;// hair colour value is not valid

    public static final int BLACK = 0;
    public static final int BROWN = 1;
    public static final int BLONDE = 2;
    public static final int RED = 3;
    public static final int GREY = 4;

    /**
     * Default constructor sets everything to 0 or null, depending on type.
     */
    public Friend() {

        firstName = null;
        surname = null;
        address = null;
        age = 0;
        height = 0;
        hairColourString = null;
    }

    /**
     * Allows the first name to be edited
     * 
     * @param first
     *            first name variable
     */
    public void setFirstName(String first) {
        firstName = first;
    }

    /**
     * Retrieves first name
     * 
     * @return first name to String
     */
    public String getFirstName() {
        return firstName;
    }

    /**
     * Allows the surname to be edited
     * 
     * @param last
     *            creates last name variable
     */
    public void setSurname(String last) {
        surname = last;
    }

    /**
     * Retrieves the surname
     * 
     * @return last name to string
     */
    public String getSurname() {
        return surname;
    }

    /**
     * Allows the address to be edited
     * 
     * @param place
     *            where the friend lives
     */
    public void setAddress(String place) {
        address = place;
    }

    /**
     * Retrieves the address
     * 
     * @return the address of the friend
     */
    public String getAddress() {
        return address;
    }

    /**
     * Allows the age (in years) to be edited
     * 
     * @param years
     *            the age in years
     */
    public void setAge(int years) {
        age = years;
    }

    /**
     * Retrieves the age in years
     * 
     * @return the age in years
     */
    public int getAge() {
        return age;
    }

    /**
     * Allows the height in centimetres to be edited
     * 
     * @param h
     *            height in centimetres
     */
    public void setHeight(int h) {
        height = h;
    }

    /**
     * Retrieves the height in centimetres
     * 
     * @return height in centimetres
     */
    public int getHeight() {
        return height;
    }

    /**
     * 
     * @return String of the personal details of the friend
     */
    @Override
    public String toString() {
        return ("First name is: " + firstName + "\nSurname is: " + surname
                + "\nAddress is: " + address + "\nAge is :" + age
                + "\nHeight is: " + height + "\nHair colour is: " + hairColourString);
    }

    /**
     * Uses JOptionPanel to edit the friend's personal details
     */
    void inputFriend()
    {
        //welcome message
        JOptionPane.showMessageDialog(null,"Weclome",null,JOptionPane.PLAIN_MESSAGE);
        //prompt to enter first name
        String name1 = JOptionPane.showInputDialog("Enter the friend's first name.");
        //calls setFirstName method
        setFirstName(name1);
        //prompt user to enter second name
        String name2 = JOptionPane.showInputDialog("Enter the friend's surname.");
        setSurname(name2);// calls setSurname method

        //prompt user to enter address
        String thisAddress = JOptionPane.showInputDialog("Enter the friend's address.");
        setAddress(thisAddress);//calls setAddress method
        //prompt user to enter age in years
        String ageString = JOptionPane.showInputDialog("Enter the friend's age in years.");
        int i = Integer.parseInt(ageString);
        setAge(i);
        //prompt user to enter height in centimetres
        String heightString = JOptionPane.showInputDialog("Enter the friend's height in cenimetres.");
        int j = Integer.parseInt(heightString);
        setHeight(j);
        //prompt user to enter hair colour
        String hairColourInput = JOptionPane.showInputDialog("Select the friend's " +
                "hair colour:\n 0 = Black\n1 = Brown\n2 = Blonde\n3 = Red\n4 = Grey");
        while(colourTrue != true)//if hair colour is valid
        {
        if(
            hairColourInput.equals("0"))
        { hairColourString = "Black";//hair is black
            colourTrue = true;}//entry is valid
        else if (hairColourInput.equals("1"))
        { hairColourString = "Brown";//hair is brown
            colourTrue = true;}//entry is valid
        else if (hairColourInput.equals("2"))
        { hairColourString = "Blonde";//hair is blonde
            colourTrue = true;}//entry is valid
        else if (hairColourInput.equals("3"))
        { hairColourString = "Red";//hair is red
            colourTrue = true;}//entry is valid 
        else if (hairColourInput.equals("4"))
        { hairColourString = "Grey";//hair is grey
            colourTrue = true;}//entry is valid
            else {
                JOptionPane.showMessageDialog(null,
                        "The number entered is invalid.", "Error",
                        JOptionPane.WARNING_MESSAGE);// warns user that entry is
                                                        // not valid
                hairColourInput = JOptionPane
                        .showInputDialog("Select the friend's " +
                        "hair colour:\n 0 = Black\n1 = Brown\n2 = Blonde\n3 = Red\n4 = Grey");
            }// user is asked to choose again until they enter a valid number

        }
    }

    /**
     * 
     * @param args
     *            Calls inputFriend method and prints out the final String using
     *            JOptionPane
     */
    public static void main(String[] args) {
        Friend friend = new Friend();
        friend.inputFriend();// calls inputFriend method
        JOptionPane.showMessageDialog(null, friend.toString()); // prints out details
    }
}

这是我对复制构造函数的尝试:

public Friend(Friend aFriend) {
    this(aFriend.getFirstName(), aFriend.getSurname(), aFriend.getAddress, aFriend.getAge, aFriend.getHeight);

以及我对一般构造函数的尝试:

public Friend2(){
    public static final int BLACK = 0;
    public static final int BROWN = 1;
    public static final int BLONDE = 2;
    public static final int RED = 3;
    public static final int GREY = 4;
}

结果是当我插入构造函数时需要一个类、接口或枚举。希望对您有所帮助。

好吧,我试过这样的复制构造函数:

public Friend(Friend f) {
this(f.getFirstName(),f.getSurname(),f.getAddress(),f.getAge(),f.getHeight());
}

但我收到一条消息说我没有合适的构造函数。

更新:通用和复制构造函数现在正在工作。感谢您的帮助。

【问题讨论】:

  • 当您尝试添加它们时遇到什么错误?
  • 请添加您为其他无法使用的构造函数尝试的代码。
  • 如果您的问题已得到解决,请接受答案或编写并接受您自己的答案。
  • 对不起,这是我第一次来这里。

标签: java multiple-constructors


【解决方案1】:

你可以像下面这样重载构造函数:

缺点1:

public Friend()
{

}

缺点2:

    public Friend(int arg)
{

}

缺点3:

    public Friend(String s)
{

}

复制缺点:

    public Friend(Friend f)
{

}

【讨论】:

  • 复制构造函数应该接受Friend 参数?
【解决方案2】:

您的Friend2() 构造函数是错误的,因为它实际上是Friend2 类的构造函数。类的构造函数都应该有一个与类名相同的方法名。 (构造函数声明看起来像方法声明,名称与类相同,但没有指定返回类型)

您的复制构造函数正在使用this 调用不存在的构造函数。 (this(x,y,z) 正在调用构造函数的 3 参数版本)

您想要的是如下所示的内容:

public class Friend 
{

// snip


/**
 * Default constructor sets everything to 0 or null, depending on type.
 */
public Friend()
{

firstName = null;
surname = null;
address = null;
age = 0;
height = 0;
hairColourString = null;
}

public Friend(Friend f) {
    // copy constructor
}

public Friend(String fName, String sName, String address, int age, int height, String hair) {
    // fill in stuff here
}

// snip 
}

【讨论】:

    【解决方案3】:

    你需要重载你的构造函数。您不能定义具有相同名称和参数的方法。在这里寻找另一个参考:

    Best way to handle multiple constructors in Java

    http://www.java-samples.com/showtutorial.php?tutorialid=284

    【讨论】:

      【解决方案4】:

      重载你的构造函数,只要确保它们有不同的签名并且它应该可以正常编译。为了保持 DRY,通过调用 this() 让副本和通用构造函数使用默认构造函数。

      【讨论】:

        猜你喜欢
        • 2019-01-24
        • 2021-12-07
        • 2017-03-21
        • 2013-09-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多