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中的多态性和接口(多态性可以用来实现接口……为什么?)
基础教程推荐
- 修改 void 函数的输入参数,然后读取 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
