Polymorphism and Interfaces in Java (can polymorphism be used to implement interfaces...why?)(Java中的多态性和接口(多态性可以用来实现接口……为什么?))
问题描述
在现实世界中,人们用它来做什么(解决什么类型的问题)?我可以看到这些一起工作的一些示例代码吗?我只能找到关于猫和狗说话或人们喝牛奶或咖啡的代码......
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?
推荐答案
当然,
以下是观察者"模式的具体示例,使用类和接口来完成记录器系统中的多态行为:
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.
这篇关于Java中的多态性和接口(多态性可以用来实现接口……为什么?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java中的多态性和接口(多态性可以用来实现接口……为什么?)
基础教程推荐
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01