As I was learning about interfaces in java, I have a question regarding the object declarations of an interface implemented class, I can create an object reference for an interface implemented class like this,
InterfaceImplementedClass testObj1 = new InterfaceImplementedClass();
And also I can create an object using the Interface reference like this,
InterfaceCreated testObj2 = new InterfaceImplementedClass();
Then what are the differences between them, which one is better to use?
The below code shows the implementation of the above explanation.
TestInterface
public interface TestInterface {
public void showOne();
public void showTwo();
}
ImplementInterface
class test implements TestInterface {
@Override
public void showOne() {
System.out.println("1");
}
@Override
public void showTwo() {
System.out.println("2");
}
}
public class ImplementInterface {
public static void main(String[] args) {
test t1 = new test();
t1.showOne(); // prints 1
t1.showTwo(); // prints 2
TestInterface1 t2 = new test();
t2.showOne(); // prints 1
t2.showTwo(); // prints 2
}
}