Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

purpose of using the interface as a reference  RSS feed

 
Christian Nash
Ranch Hand
Posts: 107
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

i really don't understand the concept of using an interface reference object.

for eg.
class A implements B{....}

interface B{}..

B interB = new A();

What does this mean? please explain the concept and the advantages behind this
 
fred rosenberger
lowercase baba
Bartender
Posts: 12541
48
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Using an interface as the reference is actually a wonderful thing. To borrow from the Head First series, say you have a Pizza interface. i can use that reference to point to ANY kind of pizza - a NewYorkStylePizza, a ChicagoStylePizza, or even an EskimoPizza.

it doesn't matter WHAT the underlying object ACTUALLY is, i just know it is an object that is garanteed to do what a pizza does.

another example you may be familiar with is the iterator interface. i may have several different kinds of collections (sets, hashmpaps, etc). I may want to iterate over all of them. since all of them have a method that returns some kind of object that implements the iterator interface, i don't have to write special code like this:



all i have to do is:
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Among other things, this helps separate things that change from things that don't change, making the code easier to maintain and less prone to breaking.

For example, you might have a method that takes a Pizza reference. As fred pointed out, this will accept any type of Pizza, so you only need one method. But this is also code that doesn't change, so you can continue to invent new types of pizzas (things that might change), and you won't need to update the method.

For this to work, note that the interface is a type of "contract" that guarantees implementing classes will have certain methods available. For example, whenever you create a new class that implements Pizza, instances of that new class are guaranteed to behave like any other Pizza, exactly as expected by a method that takes a Pizza reference.
[ November 27, 2006: Message edited by: marc weber ]
 
Justin Fox
Ranch Hand
Posts: 802
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Like in my server/client game we are doing, the ChatIF mediates between
the server and client so that different messages in the ChatClient can be interpreted from the server, and it can use the chatIF to change stuff about the ClientUI without the server doing it directly...


Justin
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!