[英]Polymorphism and Interfaces in 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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.