Javier Ferrero
Javier Ferrero

Reputation: 8811

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.

Upvotes: 4

Views: 6257

Answers (5)

qichuan
qichuan

Reputation: 620

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.

Upvotes: 0

EboMike
EboMike

Reputation: 77732

Would your design allow to make the constructor private and force construction through a static create() method?

Upvotes: 1

Matt McHenry
Matt McHenry

Reputation: 20909

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.

Upvotes: 7

templatetypedef
templatetypedef

Reputation: 372764

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.

Upvotes: 1

Hank Gay
Hank Gay

Reputation: 71939

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.

Upvotes: 2

Related Questions