Question

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?

Was it helpful?

Solution

First : using a Scanner to get an input from the external world in a constructor is a terrible idea.

Second : the constructor in Student calls the constructor in Name that takes no parameters since there is no explicit call to super(). If you want to avoid that :

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

If you don't explicitly call a super constructor from the subclass, it implicitly calls the super constructor that takes no arguments.

To make it more clear, when you write

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

you are in fact doing :

public Student(String firstName, String lastName) 
    {
        super();
        this.firstName = firstName;
        this.lastName = lastName;
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top