[英]How I can skip one method in a class extending Abstract Class?
I have one abstract class named Animal
having around 100 methods including swim
. 我有一个抽象类叫Animal
它有大约100种方法,包括swim
。
Many classes such as Dog,Cat ,Lion are extending that class. Dog,Cat,Lion等许多类都在扩展该类。
Now there is one animal Giraffe which can't swim. 现在有只不会游泳的动物长颈鹿。 But it is extending Animal
abstract class. 但是它扩展了Animal
抽象类。
I want that giraffe object does not have swim
method. 我希望该长颈鹿对象没有swim
方法。
Giraffe g = new Giraffe();
//g.swim(); // This swim should not come.
I cant change the Animal Class. 我不能改变动物等级。 One solution is to create One more abstract class copying all the methods except swim. 一种解决方案是创建另一个抽象类,该类将复制除了游泳之外的所有方法。 But this is not a good approach. 但这不是一个好方法。
How I can do this using Animal abstract class? 如何使用Animal抽象类做到这一点? Thank in advance. 预先感谢。
You can't cause java guides by contract. 您不能按合同安排Java指南。 If you are saying that an Animal
can swim then all animals can swim including a Giraffe, if it's not , then the giraffe it's not an animal. 如果您说Animal
可以游泳,那么所有动物都可以游泳,包括长颈鹿,如果不是,则说它不是动物。
The only thing you can do are without changing Animal 您唯一可以做的就是不更改Animal
@Override
public void swim(){
throw new UnsupportedOperationException();
}
The other thing you can do is making another class 您可以做的另一件事是开设另一堂课
public class Giraffe {
private final Animal a;
public Giraffe(Animal a){
this.a=a;
}
public void method1(){
a.method1();
}
public Something drink(){
return a.drink();
}
.
.
.
// and not implementing swim
}
Another is making a super-interface for Animal that don't have swim()
method and make Animal implement it. 另一个方法是为Animal创建一个不带swim()
方法的超级接口,并使Animal实现它。
You cannot skip the definition of swim()
. 您不能跳过swim()
的定义。 However, you can throw an exception for such cases. 但是,在这种情况下,您可以抛出异常。
void swim() throws CanNotSwimException{
}
我认为,最优雅的解决方案是重写方法,并抛出OperationNotSupportedException
根据情况,如果方法为void
,则也可以将其保留为空白。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.