Mirza
Mirza

Reputation: 43

difference between instantiation an interface or implementing an interface

what is the difference between creating an Object of interface and implementing an interface

example :

 public interface A{
    public void testMethod(); 

 }

on way is creating an object of interface

 public class B{
    A a = new A(){
    @override
    public void testMethod(){  //implemtation here }
     };
  }

other way is

   public class B implements A
       {
       @override
       public void testMethod(){}
       }

Upvotes: 0

Views: 1612

Answers (2)

aymen hadhraoui
aymen hadhraoui

Reputation: 61

You can't create an object of interface. Interface it's an abstract class but with all the methods are abstract. In the first code you are creating an anonymous class (i recommend you to read about this feature in java) that implements the interface A, in this case you are limited with the interface's methods even if you define additional method in your implementation you can't call it. In the second code you are creating a class that implements the interface A which means that you have a class that at least contain all the methods defined in the interface A and you can add inside your class B other methods and call its.

Upvotes: 0

Milkmaid
Milkmaid

Reputation: 1754

You are wrong:

here you anonymously implement interface and you alrady have instance of annonymouse class

 public class B{
    A a = new A(){
    @override
    public void testMethod(){  //implemtation here }
     };
  }

Here you create named implementation, you only create class without instantiate it.

 public class B implements A
       {
       @override
       public void testMethod(){}
       }

Upvotes: 4

Related Questions