I am designing a KeyPair interface which looks something like this,
public interface KeyPair {
@Deprecated
public Key firstKey();
@Deprecated
public Key secondKey();
}
I want to use this interface to implement two classes, PasswordEncryptionKeyPair
, PrivatePublicKeyPair
. But the problem is that I don't want to use the methods firstKey()
and secondKey()
as they are very generic. I rather want to use some other method and make these two method private. My current implementation is like this,
class PrivatePublicKeyPair implements KeyPair{
public Key getPrivateKey() {
return firstKey();
}
public Key getPublicKey() {
return secondKey();
}
@Override
public Key firstKey() {
return privateKey;
}
@Override
public Key secondKey() {
return publicKey;
}
}
class PasswordEncryptionKeyPair implements KeyPair{
public Key getPassword() {
return firstKey();
}
public Key getEncryptionKey() {
return secondKey();
}
@Override
public Key firstKey() {
return password;
}
@Override
public Key secondKey() {
return encryptionKey;
}
}
In the first class I want to use getPublicKey()
and getPrivateKey()
methods to return first and second key. And in next class I want to use getPassword()
and getEncryptionKey()
to return first and second key.
As an interface cannot have private method I can't make the methods private. One way this is possible is by adding body in the interface itself or create an AbstarctKeyPair
class, and make methods private there. Is there any other solution for this problem?
CodePudding user response:
You can replace inheritance with aggregation.
Add getKeyPair
method to PrivatePublicKeyPair
.
public KeyPair getKeyPair() {
return new KeyPair() {
public Key firstKey() { return getPassword(); }
public Key secondKey() { return getEncryptionKey(); }
}
}
CodePudding user response:
Since Java 9 interfaces can have private
methods (as well as default
and static
).
But you can't override a public
method (all abstract
methods in interfaces are implicitly public
) by narrowing its visibility to private
.
I'm not sure where the interface KeyPair
you've listed is coming from, but @Deprecated
annotations are a huge red flag which tells "don't use it".
You might consider declaring your own interface.
public interface KeyPair {
Key getPrivateKey();
Key getPublicKey();
}