Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java subclass constructor

Tags:

java

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.

like image 571
Javier Ferrero Avatar asked Dec 21 '22 19:12

Javier Ferrero


2 Answers

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.

like image 93
Matt McHenry Avatar answered Dec 24 '22 09:12

Matt McHenry


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.

like image 35
Hank Gay Avatar answered Dec 24 '22 09:12

Hank Gay