top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration

Facebook Login
Site Registration

Can we create an object for an interface in Java ?

0 votes

If yes then how?

posted Sep 10, 2014 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

We can't create an object without method implementations, you can achieve the same by using anonymous inner classes.

We are converting the interface to an inner class, which we haven't given a name to (hence anonymous). We have to implement all the interface's methods, then we have a class, then we create an object from it all in one statement.
Every class has a constructor, even anonymous classes. With anonymous classes we can't define our own constructors though; instead, it "inherits" all constructors of its parent class, and then redirects to that parent constructor.

1) Anonymous classes are just like local classes, besides they don’t have a name. In Java anonymous classes enables the developer to declare and instantiate a class at the same time.
2) In java normal classes are declaration, but anonymous classes are expressions so anonymous classes are created in expressions.
3) Like other inner classes, an anonymous class has access to the members of its enclosing class.

answer Sep 10, 2014 by Nikhil Pandey
Contact Us
+91 9880187415
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Karnataka INDIA.