Pemi Ng Pemi Ng - 15 days ago 5
Java Question

Create an instance of Java subclass

I would like to create an instance of the Employee class.

public class Person {
private String name;
private String address;

public Person(){

}

public Person(String name, String address){
this.name = name;
this.address = address;

}

public String getName(){
return name;
}

public void setName(String name){
this.name = name;
}

public String getAddress(){
return address;
}

public void setAddress(String address){
this.address = address;
}

@Override
public String toString(){
return getClass().getName() + "\n" + name;
}


This is the subclass Employee:

public class Employee extends Person{
private String office;


public Employee(){

}

public Employee(String office){
this.office = office;

}

public String getOffice(){
return office;
}

public void setOffice(String office){
this.office = office;
}
}


However, when I write this in the main method:

Person person1 = new Employee("ABC", "ABC@gmail.com", "NY")


Eclipse said this is not valid. But when I write

Person person 1 = new Employee("NY")


It is. I know that Employee takes one more constructor from the superclass Person. But how can I create an instance of Employee with details of Person class. Thanks a lot!

Answer

You have defined two constructors for the Employee class:

public Employee()

and

public Employee(String office)

Neither of these takes three arguments. So when you call:

new Employee("ABC", "ABC@gmail.com", "NY")

the compiler cannot find a matching constructor - hence your error.

You probably want a constructor something like this:

Employee(String name, String address, String email, String office) {
    super(name, address, email);
    this.office = office;
}

which can be called thus:

new Employee("Joe", "ABC", "joe@abc.com", "NY");