简体   繁体   中英

Java subclass constructor

This is an external class I need to extend:

public class Binary {

    public Binary( byte type , byte[] data ){
        _type = type;
        _data = data;
    }

    public byte getType(){
        return _type;
    }

    public byte[] getData(){
        return _data;
    }

    public int length(){
        return _data.length;
    }

    final byte _type;
    final byte[] _data;
}

And this is the subclass I have created:

import org.bson.types.Binary;

public class NoahId extends Binary {

 public NoahId(byte[] data) {
  //Constructor call must be the first statement in a constructor 
  super((byte) 0 , data);
 }
}

I want to force all my subclasses (NoahId) to have a byte[] data of a certain lenght or throw an Exception if not. How can I perform this kind of checks if a constructor call must be the first statement in a subclass constructor?

Using a static method to create my class allows me to do the check but I still have to define an explicit constructor.

You can do the check and throw the exception after the call to super() . If an exception is thrown at any point during the constructor, the object will be discarded and unavailable to callers.

If you're concerned about efficiency, you can write a static method that does the check and throws the exception, something like this:

super((byte) 0 , doChecks(data));

doChecks would return data unchanged if it's okay, otherwise it would throw an exception.

Make the constructor private so only your factory method can see it and do the check in the factory method. As an added bonus, the stack trace from the exception will be (slightly) nicer.

You could always throw the exception after calling the superclass constructor. This will abort construction and the client won't be able to see the malformed object. Or is there some reason that you can't call the base class constructor without being sure the data has the right length?

Alternatively, if the restrictions are always the same, you could create a private constructor for your base class that does the integrity checks.

您的设计是否允许构造函数为private并通过静态create()方法强制构造?

Because Super class constructor call must be the first statement in a constructor, there is no way to insert a statement before super();

You can always do a check after the super() call, abort the constructor call by throwing an IllegalArgument exception if the length does not meet the requirement, the instance of the subclass will be created and completed only if the constructor call is finished.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM