I have the parent class Encryption.java, which is mainly just a bunch of functions for encryption. Then I have 5 subclasses that extend that class. They all look mostly the same, except for two things: Each subclass needs a different KEYSET map, and there is also one unique function to each subclass. I’m not sure if I need inheritance or something else, the only thing changing is the KEYSET and one function
Here is an example of the subclasses
public class Keyset_1 extends Encryption{
private byte variant;
private String side;
private final Map<String,String> KEYSET = new HashMap<String,String>(){
{
put("awk_1_acq", "0123456789ABCDEF0123456789ABCDEF");
put("awk_2_acq", "0123456789ABCDEF0123456789ABCDEF");
...
}
};
//constructor is same in each subclass
public Keyset_1(byte b, String side) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException {
super();
this.variant = b;
this.side = side;
}
//Empty method in parent class, overridden here
@Override
public byte[] getZCMKVariant(){
byte[] key;
if (side.equalsIgnoreCase("acq"))
key = ISOUtil.hex2byte(KEYSET.get("zcmk_acq"));
else
key = ISOUtil.hex2byte(KEYSET.get("zcmk_iss"));
applyVariant(key, variant);
return key;
}
}
>Solution :
Generally as a rule of thumb, if you are copying code and pasting it into subclasses, that code should be in a parent class. The only thing that should be in the subclasses are unique attributes to them, so in your case this would only be the unique function in each of them.
For the KEYSET map, if it is hard coded you’ll want to use the protected keyword. This will allow each of the subclasses to have their own maps, and all you’ll need to do is place the actual data into the maps during their instantiation.
Basically, if you’re copy and pasting anything between multiple subclasses, the correct way to handle this in OOP would be to have a shared parent class between subclasses with the same code (the code you are copy and pasting).
Also, if you end up needing something like multiple inheritance, you may need to resort to using interfaces.
In terms of alternatives to inheritance, you could use delegation, but I believe in your case it may be easier to simply use more inheritance.