• Post Reply Bookmark Topic Watch Topic
  • New Topic

interface inside a class  RSS feed

 
amar nath jha
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
how to make use of interface inside a class.
what is the use of such interfaces.
 
Nathan Leniz
Ranch Hand
Posts: 132
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Interfaces contain functions that wouldn't necessarily make sense inside the superclass of your class. To steal from Head First, let's say we have a bunch of different animals.. a dog, a cat, a hippo, a giraffe, and an elephant. It makes sense that Dog, Cat, Hippo, Giraffe, and Elephant IS-A Animal, so they can directly inherit methods from animal and override them if necessary. But, Hippo, Giraffe, and Elephant wouldn't make very good pets! So if we wanted a method like scratchEar() to go to just Dog and Cat, we make an interface. Sure, you could add in the scratchEar() method to Dog and Cat, but you lose the ability to refer to those using polymorphism because Animal would need to know about those methods, and we don't really want that.

So, it may look something like this...


Interfaces just give us another handle and a way to stuff more methods in a class when those methods wouldn't make sense for the superclass. Keep in mind though that you can't access all the methods in dog if you've said it's a pet, just the ones it implements from Pet.

Edited to note: I forgot to mention that you can implement multiple interfaces in a single class!



Hope this helps,

Nate
[ December 30, 2006: Message edited by: Nathan Leniz ]
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Note: Nested interfaces are implicitly static (JLS - 8.5.2), meaning that they can be implemented without an instance of the enclosing type.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!