-2

I have learnt that we don't instantiate interfaces but this code is working fine.

Can anyone tell me why is it working?

public class Main {
    public static void main(String args[]) {
       System.out.println("Hello World!");
    }

    public interface lfrag{                        
       public void listen(String s);
    }

    lfrag lis;
}
Nicktar
  • 5,548
  • 1
  • 28
  • 43
  • 4
    You are not instantiating anything in your code. You are just declaring a variable of type ```lfrag``` – D. Lawrence Jan 16 '20 at 09:09
  • Related [What does it mean to “program to an interface?”](https://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface) – Guy Jan 16 '20 at 09:11
  • Here you are just declaring the interface type (lfrag lis;) but not instantiating. Instantiating would be lfrag lis = new ClassImplementIfragInterface(); You cannot do lfrag lis = new lfrag lis(); – Vijayanath Viswanathan Jan 16 '20 at 09:12

3 Answers3

2

In the snipped below, you only print out Hello world!:

public static void main(String args[]) {
    System.out.println("Hello World!");
}

Although you do have an interface lflag, you do not instantiate anything created inside of it, you only declare lfrag lis, which does not affect your code.

If you tried to declare lfrag lis = new lfrag(), you would have gotten an error - you cannot create an object of an interface. What you can do instead is, create a class and then implement an interface on it - this will allow you to override methods from that class in your interface.

D. Lawrence
  • 943
  • 1
  • 10
  • 23
0

You're not 'making an object'. You're just declaring a variable without initializing it. Creating variables of interface types is the use case for interfaces, so sure you can do that.

Definige a variable is making use of the contract that you created while definig the interface.

Nicktar
  • 5,548
  • 1
  • 28
  • 43
0

Lfrag lis;

Here you are creating a reference variable of type Lfrag which is allowed.Reference variables are used to access objects in the heap memory(created by new).

Cucoder
  • 1
  • 2