有构造函数的问题

时间:2013-11-26 13:25:22

标签: java constructor

这是我的代码。 在我的main函数中,我已经包含了一个构造函数。 我的客户端类中有多个构造函数

public class Client {
    private String name = "", username = "", ClientID = "", password = "";

    Client[] account = new Client[100];

    public Client() {

    }

    public Client(String name, String username) {
        // will have generated function for ClientID and also Password

        account[clientCount] = new Client();

        account[clientCount].setName(name);
        account[clientCount].setUsername(username);
        account[clientCount].setPassword(password);
        account[clientCount].setClientID(CID);
    }

    public Client(String name, String username, String password, String ClientID) {
        this.name = name;
        this.username = username;
        this.password = password;
        this.ClientID = ClientID;
    }

    public static void main(String[] args) {

        if (selection == 1) {
            Client client = new Client(); // object created called "client"

            name = JOptionPane.showInputDialog("Account Status: Admin\n" + "Please Enter Client Name: ");

            username = JOptionPane.showInputDialog("Account Status: Admin\n" + "Please Enter Client Userame: ");

            Client CLIENT = new Client(name, username);

            JOptionPane.showMessageDialog(null,
                    CLIENT.account[Client.clientCount].getName() + "\n" + CLIENT.account[Client.clientCount].getUsername() + "\n"
                            + CLIENT.account[Client.clientCount].getPassword() + "\n" + CLIENT.account[Client.clientCount].getClientID());

        }

        if (selection == 2) {
            // at here, unable to access to CLIENT object, what can I do access
            // CLIENT object to here. Or copy the same object into the other new
            // object

            for (int i = 0; i <= Client.clientCount; i++) {
                System.out.println(CLIENT.account[i].getName());
            }

        }

    }
}

1 个答案:

答案 0 :(得分:3)

只需将Client CLIENT = null;放在if-blocks之前,然后在if中使用CLIENT = new Client(name,username);。然后,您可以在if之外使用CLIENT,但如果第一个if中的代码未执行,则它将为null

实际上你的程序有一个设计错误,因为CLIENT在第二个中总是null,因为永远不会出现第一个和第二个if块在彼此之后执行的情况; - )所以你应该重新考虑你的问题。

相关问题