编写Java应用程序,主要体现父类与子类间的继承关系。父类:鸟;子类:麻雀、鸵鸟,子类继承父类的一些特点,如都是鸟,就都有翅膀、两条腿等,但它们各自又有各自的特点,如麻雀的年龄、体重;鸵鸟的身高、奔跑速度等。
时间: 2024-11-22 16:42:41 浏览: 6
java 简述父与子类的关系及构造方法
在Java中,编写一个涉及父类与子类继承的应用程序,通常会遵循"开闭原则",即对扩展开放,对修改关闭。首先,我们创建一个名为`Bird`的父类,包含所有鸟类共有的特性,比如`fly()`(飞行)和`walk()`(行走)方法:
```java
public class Bird {
protected String name;
protected int wings;
public Bird(String name) {
this.name = name;
this.wings = 2;
}
// 共享的行为
public void fly() {
System.out.println(name + " is flying.");
}
public void walk() {
System.out.println(name + " is walking.");
}
}
```
接着,我们可以定义两个子类`Sparrow`(麻雀)和`Ostrich`(鸵鸟),它们分别继承自`Bird`并添加各自的特性和行为:
```java
public class Sparrow extends Bird {
private int age;
public Sparrow(String name, int age) {
super(name);
this.age = age;
}
@Override
public void fly() {
System.out.println(name + " is flying with agility, age: " + age);
}
// 麻雀特有的行为
public void chirp() {
System.out.println(name + " is chirping.");
}
}
public class Ostrich extends Bird {
private double height;
private double runningSpeed;
public Ostrich(String name, double height, double runningSpeed) {
super(name);
this.height = height;
this.runningSpeed = runningSpeed;
}
@Override
public void fly() {
System.out.println(name + " can't fly, but runs at a speed of " + runningSpeed + " km/h.");
}
// 鸵鸟特有的行为
public void run() {
System.out.println(name + " is running at an amazing height of " + height + " meters.");
}
}
```
在这个例子中,`Sparrow`和`Ostrich`都实现了`Bird`的`fly()`和`walk()`方法,并通过覆盖(override)来提供特定于自身的版本。同时,每个子类还添加了自己特有的属性和方法。
阅读全文