1

We know,interface can never instantiate in java. We can, however, refer to an object that implements an interface by the type of the interface

public interface A
{
}
public class B implements A
{
}

public static void main(String[] args)
{
    A test = new B();  //upcating
    //A test = new A(); // wont compile
}

But I have become confused when interface is used return type,such as

Method of DriverManager class which return Connection object
public static Connection getConnection(String url);

Connection con=DriverManager.getConnection(String url);

Same problem

Method of Connection interface which return Statement object
public Statement createStatement();

Statement stat=con.createStatement();

I cannot understand,what happened when interface is used return type. Please help me by explain.

Thanks

Sakib Hasan
  • 451
  • 5
  • 17

2 Answers2

2

When an interface is used as the return type of a method, what is actually being returned is an instance of a class that implements that interface.

Eran
  • 387,369
  • 54
  • 702
  • 768
0

The returned object is than a subclass which implements said interface.

Test classes

public interface Printable {
    public String print();
}
public class A implements Printable {
    public String print() { return "I am A"; }
}
public class B implements Printable {
    public String print() { return "I am B"; }
}

Example code

private static final A a = new A();
private static final B b = new B();

public static void main(String[] args) {
    Random random = new Random(0);
    System.out.println(getA().print());
    System.out.println(getB().print());
    for (int i = 0; i < 5; ++i)
        System.out.println(getAorB(random).print());
}

public static Printable getA() {
    return a;
}

public static Printable getB() {
    return b;
}

public static Printable getAorB(Random random) {
    return random.nextBoolean() ? a : b;
}

Output

I am A
I am B
I am A
I am A
I am B
I am A
I am A
Niels Billen
  • 2,189
  • 11
  • 12