에이바바
에이바바

Reputation: 1031

Polymorphism and Interfaces in Java (can polymorphism be used to implement interfaces...why?)

In the real world what do people use this for (to solve what types of problems)? Can I see some example code of these working together? All I can find is code about cats and dogs speaking or people drinking milk or coffee...

Do people really implement polymorphism with interfaces? What for?

Upvotes: 5

Views: 20980

Answers (8)

Dhananjay
Dhananjay

Reputation: 3793

Have you wondered how LINQ in .net works ? It's all about Interfaces and polymorphism.

You need to work on projects then you will come to know about all this.

Upvotes: 0

avgvstvs
avgvstvs

Reputation: 6315

Another suggestion I'd have for "the real world" is in using spring batch. If you have a commonly used report format that follows a pattern like "pull data, create report, send to recipients" you can create an interface for your reports that enforces this standard. In this sense it works like a "template" that all batch reports would follow.

A boring example, but it's something I faced in my first year...

Upvotes: 1

J T
J T

Reputation: 5136

Sure,

Below is concrete example of the "Observer" pattern, using classes and interfaces to accomplish polymorphic behavior in a logger system:

interface ILogger{

   public void handleEvent (String event);
}

class FileLogger implements ILogger{

   public void handleEvent (String event){
       //write to file
   }
}

class ConsoleLogger implements ILogger{

   public void handleEvent (String event){
       System.out.println( event );
   }
}

class Log {

   public void registerLogger (ILogger logger){

       listeners.add(logger);
   }

   public void log (String event){

       foreach (ILogger logger in listeners){

            logger.handleEvent(event); //pass the log string to both ConsoleLogger and FileLogger!
       }
   }

   private ArrayList<ILogger> listeners;
}

Then, you could use it as follows:

public static void main(String [] args){

     Log myLog();
     FileLogger myFile();
     ConsoleLogger myConsole();

     myLog.registerLogger( myFile );    
     myLog.registerLogger( myConsole );

    myLog.log("Hello World!!");
    myLog.log("Second log event!");
}

Hope this helps your understanding of interfaces and polymorphism.

Upvotes: 16

MByD
MByD

Reputation: 137312

Almost any Java application with GUI uses it (but of course not only GUI...). For example, look at the source of android VideoView (this is the first comes to my mind...)

Upvotes: 1

Dhruv Gairola
Dhruv Gairola

Reputation: 9182

imagine "somebody" designed a huge program, with lotsa code. suppose that "that somebody" used interfaces in the design of some controller logic. now you are hired to work with this code which youve never seen before. you are asked to design a new controller class. all you need to do now is to implement the interface and make all its methods work.

if that somebody had not used interfaces, then not only would you have to redesign the controller, but you would probably need to redesign potentially the whole project because there is very strong coupling between the controller class and the rest of the classes. this will take you months just to understand the code, not to mention the new set of bugs you would probably introduce..

Upvotes: 1

iluxa
iluxa

Reputation: 6969

interface Request {
  Response execute();
}
interface Response {
  String serialize();
}
class RequestProcessor {
  void processRequest(Request r) {
    logger.log("Request: " + r);
    Response s = r.execute();
    logger.log("Response: " + s);
    connectionManager.write(r.serialize());
  }
}

Say in this example, RequestProcesor doesn't need to know about implementations of Request and Response

Upvotes: 5

corsiKa
corsiKa

Reputation: 82559

Map<String,Person> peopleByName = new HashMap<String,Person>();

If, down the road, I decide the memory overhead of HashMap is too much, I can re-do this as a TreeMap, and live with the slightly more expensive lookup times

Map<String,Person> peopleByName = new TreeMap<String,Person>();

Because peopleByName is a Map, not a TreeMap or a HashMap, all my calls are guaranteed to work on either map regardless of implementation.

This is best illustrated with the following example

public class CatsAndDogsDrinkingMilkAndCoffee {

   // what, no? :-(

}

Upvotes: 9

Peter Lawrey
Peter Lawrey

Reputation: 533492

Have a look at the code for Map/AbstractMap/HashMap as an example. You will find thousands of other examples in the JDK source which comes with the JDK (in src.zip)

Upvotes: 1

Related Questions