0

Let's say I have a class named TestClass that implements interface named TestInterface. What is the difference in creating following objects:

TestInterface test1 = new TestClass();
TestClass test2 = new TestClass();

If there is no differences, which one is the better convention?

user13630431
  • 23
  • 1
  • 6
  • 1
    using test1 object, you can only access to the methods declared in the TestInterface whereas using test2, you can access to all the methods and proprrties defined in TestClass. – Md Shahbaz Ahmad Jul 13 '20 at 15:29
  • [This](https://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface) might help. – Andrew S Jul 13 '20 at 15:31
  • 1
    I would recommend reading about "coding To Interfaces".. A simple example : https://medium.com/javarevisited/oop-good-practices-coding-to-the-interface-baea84fd60d3 – Rahul Singh Jul 13 '20 at 15:34

1 Answers1

0
interface TestInterface {
    public void function2();
}

public class TestClass implements TestInterface {
    public static void main(String... args) {
        TestInterface testInterface = new TestClass();
        TestClass testClass = new TestClass();

        /* function1 belongs to TestClass class only */
        testInterface.function1(); // This gives you compile time error as function1 doesn't belong to TestInterface
        testClass.function1(); // Whereas this is ok.

        /* function2 belongs to TestInterface and TestClass, so function2 can be called from both object (testClass and testInterface) */
        testInterface.function2(); 
        testClass.function2();
    }
    public void function1() {
        System.out.println("This is function 1");
    }
    public void function2() {
        System.out.println("This is function 2");
    }
}
Md Shahbaz Ahmad
  • 345
  • 4
  • 12