Better way to add fields to superclass in Java I'm making my first steps in OOP and I'm currently doing some exercises. I've done a simple program with class structure like this (I'll provide only essential parts):

Super class:

public abstract class Employee {
    private String lastName;
    private float salary;

    public Employee(String lastName, float salary) {
        this.lastName = lastName;
        this.salary= salary;
    }
}


And several child classes, all similar to this:

public class Worker extends Employee {
    private float hourRate;

    public Worker (String lastName, float salary, float hourRate) {
        super(lastName, salary);
        this.hourRate = hourRate;
    }
}


My concern is, when I'll decide to add some field to the Employee class that have to be set in constructor, let's say firstName, than I have to add it there and in constructor's arguments of all child classes and where I call super() inside them. It doesn't seem to be the best solution... Is there a better way to do such a thing? Maybe there is some pattern I don't know yet?
Short answer: no, there's no better way.

There's also nothing wrong with this way of working. You're adding a field that every instance of this class needs to have for your program to work correctly. That's a good reason to enforce initialising it in the constructor. Your compiler (or even better, your IDE) will tell you where else you need to update your code.



In case you're developing a package that other people use where they need to have some time to adjust to the new version you need to be more careful when making API changes (like adding parameters to a public constructor).

In that case you make the current constructor @deprecated and provide a new one next to it. You can also provide a default value for the new field so that the original constructor still "works". For example:

public class Person {
    private String lastName;
    private String firstName;

    @deprecated
    public Person(String lastName) {
        this("", lastName);
    }

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

    ...


This way, their IDE will still tell them they're using an outdated constructor, but at least they'll still be able to run their current code without changing all the calls from the start.



Alternatively you could look into other options besides adding the fields to that class. For example, you could have a lookup class that, given a certain employee, looks up his salary in a table for example. This greatly depends on what your program is supposed to do. With the little information you've given us here it's hard to propose concrete solutions like this.