2

I am not very well rounded in Java, which is why I am asking this question that is probably very stupid sounding. Nonetheless, I am trying to figure out how to ignore a class's default construct method, and use a construct method with parameters instead. For example, something like this:

public class Name {

    String firstName, lastName;

    public Name()
    {
        String dialog = JOptionPane.showInputDialog("First and Last name: ");
        Scanner inName = new Scanner(dialog);
        firstName = inName.next();
        lastName = inName.nextLine();
    }

    public Name(String newFirst, String newLast)
    {
        firstName = newFirst;
        lastName = newLast;
    }

}

I then have a class called Student which extends name as such:

public class Student extends Name
{

    public Student(String firstName, String lastName) 
    {
        firstName = firstName;
        lastName = lastName; 
    }

}

So, the first construct method from Name class prompts the user to enter their name, but say I already know the user's name and have it stored in some variables, how can I create a new Student() object (which is really a name() object) without invoking that first default constructor, and instead invoke it as such:

Student student1 = new Student(firstName, lastName);

I understand why the following line would call the default construct method:

Student student1 = new Student();

But the next following line stil calls the same parameterless construct method, even though I am using parameters:

Student student1 = new Student(firstName, lastName);

What am I doing wrong here?

4

1 回答 1

6

首先:在构造函数中使用 Scanner 从外部世界获取输入是一个糟糕的主意。

第二:Student 中的构造函数调用 Name 中不带参数的构造函数,因为没有显式调用 super()。如果你想避免这种情况:

 public Student(String firstName, String lastName) 
    {
        super(firstName, lastName);
    }

如果您没有从子类中显式调用超级构造函数,它会隐式调用不带参数的超级构造函数。

为了更清楚,当你写

public Student(String firstName, String lastName) 
    {
        this.firstName = firstName;
        this.lastName = lastName;
    }

你实际上在做:

public Student(String firstName, String lastName) 
    {
        super();
        this.firstName = firstName;
        this.lastName = lastName;
    }
于 2013-05-22T21:45:00.107 回答