简体   繁体   中英

Is PublicKey and PrivateKey in java a Class or an Interface

As i have came to known through https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/security/PublicKey.html that it is an interface.But an Interface cannot create an object but using the code

public static void main(String[] args) throws Exception {
    try
    {
    KeyPairGenerator kpr=KeyPairGenerator.getInstance("EC");
    SecureRandom sr=SecureRandom.getInstance("SHA1PRNG");
    ECGenParameterSpec ecgps=new ECGenParameterSpec("secp256r1");
    kpr.initialize(ecgps,sr);
    KeyPair kp=kpr.generateKeyPair();
    PublicKey p=kp.getPublic();
    System.out.println(p);
    }
    catch(Exception e)
    {
        throw new RuntimeException(e);
    } 

its still working.Can anyone explain this How??I am using Eclipse IDE(openjdk12).

The implementation has some class that implements the PublicKey interface. During the call to generateKeyPair the implementing class is created, and is cast to PublicKey before it is returned to you. This is a basic "factory design template".

Example:

// you see this
interface Foo
{
    void bar();
}

// we hide this somewhere and do not provide the code
class FooImpl
{
    void bar() { ... }
}

// This is the factory that you'll be using
// it will provide you with an instance that implements Foo
class FooGenerator
{
    Foo generate() { return new FooImpl(); }
}

Try calling p.getClass().getName() and see for yourself!

PublicKey and PrivateKey are interfaces, as you can see from the linked documentation.

But an Interface cannot create an object...

That's not actually true (default methods can create objects), but that's not what's happening. The object is being created by KeyPairGenerator . The objects in the keypair will be instances of classes that implement the PublicKey and PrivateKey interfaces.

It's exactly like:

Map<String> map = new HashMap<>();

Map is an interface, but HashMap is a class; the map assigned to the variable is an instance of HashMap . Code in the KeyPairGenerator implementation being used will create objects in a similar way, ones that are instances of classes implementing PublicKey and PrivateKey .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM