How do you override the parent constructor in Java?

Ampage Green :

I currently have a class, let's call it Person, with a constructor like so.

public class Person
{
    private String name;

    public Person(String name)
    {
        this.name = name;
        System.out.println("This person is: "+getName());
    }

    public String getName()
    {
        return this.name;
    }

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

Then we inherit the class with a more specific type of Person, in this case an Employee.

public class Employee extends Person
{
    private int id;

    public Employee(String name, int id)
    {
        super(name);
        this.id = id;
        System.out.println("This person is: "+getName()+", identified by #"+getId());
    }

    public int getId()
    {
        return this.name;
    }

    public void setId(int id)
    {
        this.id = id;
    }
}

I am wanting to make it such that Employee prints it's own statement when the object is created, but instead it is printing both the print statement from Person and also from Employee. How can I override this statement to keep that from happening? Is there a better way to print to the console that will prevent this from occurring?

T.J. Crowder :

How can I override this statement to keep that from happening?

You can't, unless you can edit Person to provide a constructor that doesn't do the System.out.println call. A subclass must call one of its superclass constructors.¹ Your Person class has only the one, which includes the System.out.println call, so Employee has no choice but to call it.

This is one of several reasons constructors shouldn't have side-effects. Neither Person nor Employee should be calling System.out.println. That should be left to code using the class, or a method (rather than constructor).


¹ If you don't do it explicitly, the compiler will insert super() at the beginning of your constructor. In your case, that would be a compilation error, because Person doesn't have a zero-parameters constructor.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=115818&siteId=1