创建Children类java
时间: 2024-10-17 19:10:57 浏览: 18
创建一个名为"Children"的Java类,通常包含一个或多个子类,可以代表有共同特性的孩子群体,例如学生、运动员等。下面是一个简单的示例,展示了如何创建一个基础的Children类和两个子类:
```java
// Children 类作为基类或抽象类
public abstract class Children {
private String name;
protected int age;
// 构造函数
public Children(String name, int age) {
this.name = name;
this.age = age;
}
// 获取和设置名字的方法
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
// 返回年龄的方法
public int getAge() {
return age;
}
// 抽象方法,每个子类需要实现
public abstract void play();
}
// 子类1 - Student
public class Student extends Children {
private String grade;
public Student(String name, int age, String grade) {
super(name, age);
this.grade = grade;
}
@Override
public void play() {
System.out.println(getName() + " is studying in grade " + grade);
}
}
// 子类2 - Athlete
public class Athlete extends Children {
private String sport;
public Athlete(String name, int age, String sport) {
super(name, age);
this.sport = sport;
}
@Override
public void play() {
System.out.println(getName() + " is playing " + sport);
}
}
// 主程序部分
public class Main {
public static void main(String[] args) {
Student student = new Student("Alice", 10, "5th");
student.play(); // 输出: Alice is studying in grade 5th
Athlete athlete = new Athlete("Bob", 12, "Basketball");
athlete.play(); // 输出: Bob is playing Basketball
}
}
```
在这个例子中,Children是抽象的,它的`play()`方法被声明为抽象方法,子类Student和Athlete都实现了这个方法。这展示了多态的一个基本应用。
阅读全文