[英]Is there any way to access a sub-type method without casting using generic
To access sub-class method down-casting is needed, is there is a way to achieve this using generic without type-casting in same manner.要访问子类方法需要向下转换,是否有一种方法可以使用泛型而不以相同的方式进行类型转换来实现这一点。
public class Main {
public static void main(String[] args){
Animal parrot = new Bird();
((Bird)parrot).fly();
}
}
interface Animal{
void eat();
}
class Bird implements Animal{
@Override
public void eat() {}
public void fly(){}
}
public class Main {
public static void main(String[] args){
Animal parrot = new Bird();
parrot.move();
}
}
interface Animal{
void eat();
void move();
}
class Bird implements Animal{
@Override
public void eat() {}
public void move(){fly();}
public void fly(){}
}
It could work with something like this I guess我猜它可以用这样的东西
Interfaces are meant to add methods to implemented classes without defining actual code for this method, meaning that any implemented class will definitely have the same methods but 2 implemented methods with the same name won't necessarily perform the same action.接口旨在向已实现的类添加方法,而无需为此方法定义实际代码,这意味着任何已实现的类肯定会具有相同的方法,但 2 个具有相同名称的已实现方法不一定执行相同的操作。
To explain it with the current thread it would be:用当前线程解释它应该是:
interface Animal {
void move();
}
class Bird implements Animal{
public void move(){
fly();
}
}
class Dog implements Animal{
public void move(){
walk();
}
}
This way, each class will have its own definition of the move method while in main
each method will be called by object.move()
.这样,每个类都有自己的 move 方法定义,而在main
每个方法都将由object.move()
调用。
This way of doing things allows to go from a code like this这种做事方式允许从这样的代码开始
for (object tmp:objList){
if(tmp.class=="Bird")
tmp.fly();
}
else if (tmp.class=="Dog"){
tmp.walk();
}
...
}
to到
for (object tmp:objList){
tmp.move();
}
The parrot class should extend the Bird class, then you can call the fly method from a parrot object directly and without need to cast. parrot 类应该继承Bird 类,这样就可以直接从parrot 对象调用fly 方法,不需要强制转换。
public class Parrot extends Bird{
//have some filed or method
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.