Polymorphism and interfaces in Java (you can use polymorphism to implement interfaces… Why?)

In the real world, what types of problems do people use it to solve? Can I see the sample code for these collaborations? All I can find is the code about cats and dogs talking or people drinking milk or coffee

Do people really implement polymorphism with interfaces? What's your job?

Solution

of course,

The following is a specific example of the "Observer" mode, which uses classes and interfaces to complete polymorphic behavior in the recorder 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;
}

You can then 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!");
}

Hopefully this will help you understand interfaces and polymorphism

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>