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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With