Java继承层次动物类

标签 java inheritance polymorphism multiple-inheritance

我的 java 项目中应该有一个动物层次结构,但我对什么应该扩展什么感到困惑。 以下是说明:

Write classes or interfaces to represent the following:

  • Adoptable
  • Animal
  • Bat
  • Bird
  • BlueWhale
  • Dog
  • Emu
  • Fish
  • Goldfish
  • Mammal
  • Otter
  • Parakeet
  • Reptile
  • Turtle
  • WaterDweller
  • Whale
  • Winged

You need to decide on the structure of the classes/interfaces. Consider:

Which should be an abstract class? a concrete class? Which should be an interface? How should the classes be related through inheritance? In what classes should methods be placed? What methods should be overridden? What information should be taken in as a parameter and what information can be hard-coded into a class? Some additional details/requirements:

All animals have a method "isWarmBlooded" that returns a boolean. The method can be in the class directly or inherited. All animals have a name. All classes have a toString method that returns the animal's name, whether the animal is warm blooded, and a list of all animal names that apply to the animal. The toString method can be in the class directly or inherited. Animals that can be adopted as pets have a method "getHomeCareInstructions" that returns a description of how to care for the animal. Animals that live in water (are water dwellers) have a method "livesOnLand" that returns a boolean of whether the animal also can live on land. Animals that have wings have a method "flies" that returns a boolean of whether the animal can fly. This part of the assignment isn't necessarily difficult from a programming perspective. What you should spend time on is carefully considering the design of you classes and how they should be related through inheritance or interfaces

我不知道如何设计这个,因为我知道鸟是有翅膀的,但 bat 也是。因此 bat 会伸出翅膀,但 bat 也是哺乳动物。我不可能拥有有翅膀的哺乳动物,因为鸟类不是哺乳动物。此外,鲸鱼和水獭是水栖动物,但也是水栖动物。我不能让水生动物延伸到哺乳动物(因为鲸鱼/水獭是哺乳动物),但鱼不是哺乳动物,而是水生动物。我怎样才能让 bat 既是有翅膀的又是哺乳动物?编程是简单的部分,只是在项目结构上遇到困难。我该如何构建它才能工作?

最佳答案

所以在你的建模中你必须思考:

哪些是真正的动物?

例如鲸鱼、水獭 -> 类

哪些是动物类型

例如一只鸟。 -> 抽象类

因为每只鸸鹋都是鸟。
这称为里氏替换原理 https://en.wikipedia.org/wiki/Liskov_substitution_principle

动物有哪些特征

例如WaterDweller、Winged -> 这些是接口(interface)。

每个类都可以有一个父类(super class),它可以有很多特征,比如有翅膀,或者是水居者,或者是可收养的

为您的 bat 示例添加一个内容:

一种哺乳动物 -> 因此它的父类(super class)是哺乳动物。它有翼——这是一个特征——所以它实现了有翼接口(interface)。

class Bat extends Mammal implements Winged{
}

关于Java继承层次动物类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53117364/

相关文章:

C# 到 C++ 多态性

java - 如何在另一个应用程序中执行后退按钮操作?

java - 使用 Java 查找和替换文本文件中的单词

javascript - ExpressJS 子类在回调中缺少继承的属性和属性

c# - 组合应该专门用于继承还是在某些情况下不应该使用?

c++ - 我怎样才能实现一个函数来调用任何(任意)函数及其(任意)参数?

c++ - 实现抽象工厂模式的最佳方法

java - 如何在jsp中检索属性文件名?

Java转换UTC/CET时间

java - 多个父类(super class)和代码重用