Search code examples
javafieldtype

Restricting types of fields of subclasses


There are four classes: A, B, C and A1 that extends class A. I have to restrict type of fields of A1 to be only instances of B or C.

I mean any subclasses of A can have arbitrary number of fields of type B or C, but not of any other type. For example here three classes:

public class A1 extends A{
    B b1;
    B b2;
    C c1;
}

public class A2 extends A{
    B b1;
}

public class A3 extends A{
    B b1;
    B b2;
    sometype s;

}

So A1 and A2 are valid and A3 is not.

How I can do that?


Solution

  • You cannot* restrict any** fields of which the subclass creates, simply by inheriting from the parent class.

    From the Oracle JavaTM Tutorials - Inheritance, it was written that:

    What You Can Do in a Subclass

    • You can declare a field in the subclass with the same name as the one in the superclass, thus hiding it (not recommended).
    • You can declare new fields in the subclass that are not in the superclass.

    Instead, this is a sign of an incorrect design pattern. Consider creating a Builder of A, and then restricting the creation of As through building:

    new A.Builder().add(b)...
    

    -  * However, you can instead create an initializer in your parent class that checks for all present fields of the class. Minus the fields of the parent class, the rest are fields of the subtype. By throwing an ExceptionInInitializerError, you realistically invalidate the operation. Unfortunately, you can only check for visible fields with reflection.
    -  ** However, you can write a custom ClassLoader which only loads classes that are considered valid by doing checks on the object and deciding not to load them when appropriate. This is a lengthy topic and is not a viable approach.