Java – immutable classes and subclasses

I'm trying to learn variable / immutable classes. I met this post

Some of the answers provided are: @ h_ 419_ 3@

OK, I see, but how will you deal with this problem Suppose you are given the task of creating three employee classes, accounting, itdepartment and qualityassurance Now, you can create an abstract class named employee, which contains common methods shared by everyone (employee ID, name, salary, etc.), and your class is no longer immutable@ H_ 419_ 3@

Using Java, how do you solve this problem? Will you create three classes to make them final classes without implementing abstract methods? (so, there are no subclasses) or would you use an interface and only provide getters@ H_ 419_ 3@

Solution

This is almost true, but not entirely Again: @ h_ 419_ 3@

The problem with allowing subclassing is that usually anyone who can create a class can subclass any public non final class@ H_ 419_ 3@

But all subclasses must call one of their superclass constructors A package private constructor can only be called by subclasses in the same package@ H_ 419_ 3@

If you use seal packages to control which classes in the package, you can limit subclassing First define a class you want to subclass: @ h_ 419_ 3@

public abstract class ImmutableBaseClass {
  ImmutableBaseClass(...) {
    ...
  }
}

Since all subclasses must have access to the super constructor, you can ensure that all subclasses in the package you define follow immutable rules@ H_ 419_ 3@

public final class ImmutableConcreteClass extends ImmutableBaseClass {
  public ImmutableConcreteClass(...) {
    super(...);
  }
}

To apply this to your example, @ h_ 419_ 3@

public abstract class Employee {
  private final Id id;
  private final Name name;

  // Package private constructor in sub-classable class.
  Employee(Id id,Name name,...) {
    // Defensively copy as necessary.
  }
}

public final class Accountant extends Employee {
  // Public constructos allowed in final sub-classes.
  public Accountant(Id id,...) {
    super(id,name,...);  // Call to super works from same package.
  }
}

public final class ITWorker extends Employee {
  // Ditto.
  public ITWorker(Id id,...);
  }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>