简体   繁体   中英

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 .

Many classes such as Dog,Cat ,Lion are extending that class.

Now there is one animal Giraffe which can't swim. But it is extending Animal abstract class.

I want that giraffe object does not have swim method.

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? Thank in advance.

You can't cause java guides by contract. 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.

The only thing you can do are without changing 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.

You cannot skip the definition of swim() . However, you can throw an exception for such cases.

void swim() throws CanNotSwimException{
}

我认为,最优雅的解决方案是重写方法,并抛出OperationNotSupportedException

根据情况,如果方法为void ,则也可以将其保留为空白。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM