Java subclass constructor

This is the outer 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 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 byte [] data of a certain length or throw an exception if not. How can I perform such checks if the constructor call should be the first statement in the constructor of the subclass?

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

+4
source share
5 answers

You can check and throw an exception after calling super() . If an exception is thrown at any time during the constructor, the object will be discarded and not accessible to callers.

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

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

doChecks return data unchanged if it is ok, otherwise it will throw an exception.

+8
source

Create a private constructor so that only your factory method can see it and perform a check in the factory method. As an added bonus, stack tracing from an exception will be (slightly) nicer.

+2
source

You can always throw an exception after calling the constructor of the superclass. This will lead to the cessation of construction, and the client will not be able to see the distorted object. Or is there a reason why you cannot call the constructor of the base class without being sure that the data is of the correct length?

Alternatively, if the constraints are always the same, you can create a private constructor for the base class that checks for integrity.

+1
source

Will your construction allow you to make the constructor private and force the construction of the construct using the static create () method?

+1
source

Since the constructor call to the Super class must be the first statement in the constructor, it is not possible to insert an operator before super();

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

0
source

Source: https://habr.com/ru/post/1335015/


All Articles