java 多态性 接口_Java中的多态性和接口
我是
java的新手,我正在學習接口和多態.我想知道最好的方法是什么.
假設我有一個簡單的課程.
class Object{
// Renders the object to screen
public void render(){
}
我想提供一些對象可以做的東西,雖然是一個接口:
interface Animate{
// Animate the object
void animate();
}
如果我想實現動畫的界面,我可以執行以下操作:
class AnimatedObject extends Object implements Animate{
public void animate() {
// animates the object
}
}
因為所有非對象都可以動畫我想要通過多態來處理動畫的渲染,但是不知道如何使用InstanceOf來區分對象,而不必詢問它是否實現了接口.我計劃將所有這些對象放在一個容器中.
class Example {
public static void main(String[] args) {
Object obj1= new Object();
Object obj2= new AnimatedObject();
// this is not possible but i would want to know the best way
// to handle it do i have to ask for instanceOf of the interface?.
// There isn't other way?
// obj1.animate();
obj1.render();
obj2.animate();
obj2.render();
}
}
總結
以上是生活随笔為你收集整理的java 多态性 接口_Java中的多态性和接口的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: centos 7.0上RabbitMQ
- 下一篇: java避免内存泄露_Java防止非静态