【问题标题】:Java - Inheritance and PolymorphismJava - 继承和多态
【发布时间】:2019-02-22 10:17:37
【问题描述】:

说明如下: 创建一个包含 main 方法的 Main 类。实施 main方法里面有以下内容:

– 使用重载的构造函数从常规类创建对象

– 测试所有实例方法(即setter、getter、重载、覆盖)

– 分配给子对象的父引用

——传递多态对象的方法调用

我被困在我的父类中,即雨林。接下来我该怎么做?

雨林班

//INHERITANCE                                                      
  package com.ancient;                                              
  public class Rainforest                                                
  {                                         
  public static void main(String[] args)                                 
  }

Rainforest Class - Inherits Parent and Child

哺乳动物类(父类)

//PARENT CLASS                                                     
  package com.ancient;                                              
  public class Mammal                                                    
  {
//INSTANCE VARIABLES
private String type;
private double speed;

//CONSTRUCTOR
public Mammal(String type, double speed)
{
    this.type = type;
    this.speed = speed;
}

//SETTERS
public void setType(String type) 
{
    this.type = type;
}

public void setSpeed(double speed) 
{
    this.speed = speed;
}

//GETTERS
public String getType() 
{
    return type;
}

public double getSpeed() 
{
    return speed;
}

//OVERRIDDEN
public void hunt(int Food)//int Food is the quantity - how many does the eagle he hunts?
{
    System.out.println("The Bald eagle preys " + Food + "animals within a day to survive.");
}

}

Mammal Class - Part 1 Mammal Class - Part 2

鸟(儿童班)

package com.ancient;                                                
 public class Bird extends Mammal                                        
 {                                                                  
 public Bird(String type, double speed) 
{
    super(type, speed);
}

//OVERRIDDING
public void hunt(int Food)//int Food is the quantity - how many does the eagle he hunts?
{
    System.out.println("The Bald eagle will prey " + Food + "animals within a day to survive.");                                                  
}                                                                        
}

Bird - Child Class

我的项目内容 Project content > src > package (library) > regular (2) and main classes (1)

现在,这里的问题是:我的构造函数是未定义的。我应该制作一个新包并将 Rainforest 类插入其中吗?或者我在哺乳动物和鸟类类中的对象有问题?

【问题讨论】:

  • 不要发布你的代码图片。直接放你的代码。

标签: java inheritance polymorphism parent-child


【解决方案1】:

您的 Mammal 类中有一个构造函数,它接受参数,但您试图在不传递参数的情况下实例化您的对象。

【讨论】:

  • 喜欢这个“公共哺乳动物(字符串类型,双倍速)”?
  • 这就是您在 Mammal 类中定义构造函数的方式。要实例化一个新的 Mammal 对象,您需要将参数传递给您的构造函数,例如新哺乳动物(“类型”,1.0);
猜你喜欢
  • 2016-01-24
  • 2020-01-06
  • 2011-12-19
  • 2012-12-23
  • 2014-05-24
  • 1970-01-01
  • 1970-01-01
  • 2018-04-18
相关资源
最近更新 更多