13

Is it possible to create an object for an interface? If yes, how is it done? According to my view the following code says that we can:

Runnable r = new Runnable() {
    // some implementation
}
cup
  • 7,589
  • 4
  • 19
  • 42
kalepu harish
  • 139
  • 1
  • 1
  • 3

8 Answers8

20

This is not creating the instance of Interface, it is creating a class that implements interface. So when you write:

Runnable runnable = new Runnable() {
    @Override
    public void run() {
        // TODO Auto-generated method stub

    }
};

You are actually a creating a class that is implementing the Runnable interface. You need to follow all rules here, here, we are overriding the run method for Runnable. There is similar thing for abstract class also. We can test using an example:

public abstract class AbstractClass {
    public void someMethod() {
        System.out.println("abstract class");
    }
}

and another class i.e. TestClass:

public class TestClass {
    public static void main(String[] args) {
        AbstractClass abstractClass = new AbstractClass() {
            public void someMethod() {
                System.out.println("concrete class method");
            }
        };
        abstractClass.someMethod();
    }
}

This will create the instance of a subclass in which we are overriding someMethod(); This program prints:

concrete class method

This proves we are creating the instance of subclass.

Community
  • 1
  • 1
Prasad Kharkar
  • 13,410
  • 5
  • 37
  • 56
13

You can't instantiate an interface directly, but you can instantiate a class that implements that interface:

public class RunClass implements Runnable {
    // Class implementation
}

Runnable r = new RunClass();

This is basically the same as what you're doing inline. The brackets after new Runnable() will contain your implementation inline.

JREN
  • 3,572
  • 3
  • 27
  • 45
9

You can create an anonymous inner class:

Runnable r = new Runnable() {
    @Override
    public void run() {
    }
};

Therefore you create a new class which implements the given interface.

Uwe Plonus
  • 9,803
  • 4
  • 41
  • 48
8

Is it possible to creating object for an interface?

No. The code you've shown creates an object from an anonymous class, which implements the interface. Under the covers, the JVM actually creates a class implementing the interface, and then creates an instance of that class.


The "anonymous" class generated will actually have a name, based on the name of the class in which this code appears, for instance YourClass$1 or similar. E.g.:

public class AnonymousName {
    public static final void main(String[] args) {
        Runnable r = new Runnable() {
            public void run() {
            }
        };

        System.out.println(r.getClass().getName());
    }
}

...outputs

AnonymousName$1

(At least on Oracle's JVM; I don't know if the naming convention is in the JLS or if it's JVM-specific behavior.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
3

Here's my understanding.

An interface

public Interface SomeInterface{
}

You can declare an Object for an interface.

SomeInterface anObject;

You cannot instantiate this object directly using this interface. However, let's say you have a class that implements this interface.

public class SomeClass implements SomeInterface {}

Then you can do this,

anObject = new someClass();

(This is conceptually of course (like pseudocode) actual code may vary depending on your classes and access modifiers etc.)

I'll update as to why exactly we are doing this/what the point is as soon as I find out.

Note: Some of this has been mentioned in above answers, just want the OP to know this whole thing too.

SilverNak
  • 3,283
  • 4
  • 28
  • 44
Bugsy
  • 65
  • 1
  • 9
  • This is done to achieve abstraction, a concept to hide the details of the actual implementation while giving the output. Eg: There can be multiple instances created but with only single reference of the interface-- anObject1 = new FirstClass(); anObject2 = new SecondClass(); anObject3 = new ThirdClass(); corresponding to the references, the corresponding methods in the 3 classes will be triggered. Purpose ? The purpose of using anObject as a reference variable is because at runtime, we dont know which instance will be created.. This is done to achieve loose coupling . – Shubham Uniyal Apr 29 '21 at 13:47
0

we can not instatiate the interface (since do not have constructor).

Gaurav Manral
  • 600
  • 4
  • 7
  • 24
0

What you are seeing is an anonymous inner class.

it’s creating an instance of a new, anonymous,implementer of Runnable class.

Because an anonymous class definition is an expression, it must be part of a statement.

Community
  • 1
  • 1
bNd
  • 7,512
  • 7
  • 39
  • 72
0

You cannot create Object of interface, but you can create Object of class that is extends interface.

Like if you like to create an Object of Interface Laptop and declare method void writeCode() and implement this method in class class Development you can use concept of anonymous inner class concept.

now you can create object of anonymous inner class object reference or type of Interface Laptop

public interface Laptop {
    public abstract void writeCode();
}
public class Developer implements Laptop{
    public void writeCode() {
        System.out.println("In developer Class");
    }
}
public class Main {
    public static void main(String[] args) {
        Laptop lap = new Laptop() {
            @Override
            public void writeCode() {
                System.out.println("In new Method");
            }
        };

        lap.writeCode();
    }
}
  • 1
    there is no need for the `Developer` class in posted code at all - an anonymous class does not need another non-anonymous class... BTW the question is 10 years old! – user16320675 Aug 15 '23 at 07:18