• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Understaning Interfaces

 
Rajat Bhatia
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am new to the java.

I have a doubt regarding interfaces. In java you cannot create objects of interfaces as they are represent abstract structure which needs to be implemented by other classes.

If any class wants to implement an interface it has to explicitly mention implements keyword.
But I do not think same is true with anonymous inner classes.

Suppose I have an interface like



And here is my Test class. No where it mentions that it implements HelloInterface.


My doubt is inside getHello method we return an instance of HelloInterface interface as it is appended with new operatror.

How can we create object of HelloInterface as it is an interface?Also we have not mentioned that the inner class is implementing HelloInterface?

When I tried printing hello reference,it showed that the reference points to an object of Test type. How come hello is of type Test as it was created using new HelloInterface() ?
 
Darryl Burke
Bartender
Posts: 5126
11
Java Netbeans IDE Opera
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rajat Bhatia wrote:inside getHello method we return an instance of HelloInterface interface

No, you return an instance of an anonymous inner class that implements the HelloInterface. If you look at the results of compiling Text.java, you will find that two class files are created, one for the outer class and one for the inner class.

When I tried printing hello reference,it showed that the reference points to an object of Test type.

Look more closely. What do you see? (hint: $1)

And welcome to the Ranch, Rajat! For your future posts, please learn to UseCodeTags <- link to retain code formatting for readability.
 
micha koern
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As you allready mentioned- you are using a anonymous classes.

An anonymous class can either implement an interface or extend a class (not both).
What to do depends on the class/interface you use.
In your case HelloInterface is an Interface so



ist the same as



There is one difference the anonymous class has no Name.

Because of this you are not instantiating the Interface. - You are instantiating the Anonymous class that implements the interface.

But i cant explain why hello should be of Type Test - i think this is a debugger-Problem.


 
Campbell Ritchie
Sheriff
Pie
Posts: 48940
60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch I think you have already got adequate answers to your question. I have added code tags to your post, which you should always use, and you can see how much better it looks
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic