1

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
    }
}
Ajay
  • 35
  • 1
  • 6
  • Look, interface `IHuman` have method `speak()`, now ajay and aashish both can speak in different accent, means different implementation, but they both do same task of speak(), its not advisible to do `ajay aj = new ajay() or ashish aa = new ashish()` rather do, `IHuman human = new ajay() or new ashish()` – Ashish Kamble Oct 15 '19 at 11:55
  • The reason why people prefer to use interfaces is because it only defines *what a class can do*, and not *how its done*. This allows you to create very clean looking systems where you can, for instance, have moving objects. One can be a human, a box that can slide, or an enemy. Each of them can move but do so with different rules, maybe an enemy moves less or differently than a human does. A box can only move straight lines and one tile at a time. By using an interface you allow each class to implement it's own behaviour on the defined set of *required* functionalities. – martijn p Oct 15 '19 at 12:15
  • This also allows you to use interfaces in some variables while allowing multiple different object types to occupate the variable. With the previous example you could have a tile containing an "Object", it's properties could be that an object can move and an object can collide. By defining these properties you can then implement multiple classes that can occupate the tile without requiring more than 1 variable. You can place each object on the tile, while still allowing you to access it's core functionality – martijn p Oct 15 '19 at 12:17
  • Thanks everyone for your brief explanation, I am starting to understand the concepts now. – Ajay Oct 15 '19 at 15:52

0 Answers0