- 实验名称
类的继承
- 实验目的及要求(本次上机实验所涉及并要求掌握的知识点)
- 掌握类的继承中构造方法,成员属性,实例方法的继承。
- 掌握抽象类的定义与使用。
- 实验环境(本次上机实践所使用的平台和相关软件)
多媒体微型计算机;Windows ,jdk及Eclipse。
- 实验设计
- 实验内容
(1)子类通过调用父类的构造方法给父类属性赋值。
定义父类Person,包含身份证号id,姓名name成员变量,同时包含两个构造方法:一个带参数的,为对象各个成员变量赋值,另一个是空参数的,将对象赋值为系统默认值;
同时还含有对应的设置方法及访问方法及eat方法,输出吃的食物,其中食物是参数;
walk方法,输出走了多少路程,其中路程是参数;
定义子类Student(主类),在父类的基础上新增了学号studentId和成绩score两个成员变量,两个构造方法,
新增两个方法:studyCourse方法输出今天学习的课程,其中课程名是参数;test方法输出参加考试的科目,其中科目是参数。
在main方法中,创建一个人,身份证号为1234567,姓名张三,假设他今天走了1000米,吃了饺子,输出张三的个人信息,包括身份证、姓名、所走的路程及吃了什么;创建一个学生(就是自己),输出个人信息,包括身份证、姓名、所走的路程、吃的食物及今天学习的课程和考试科目;
(2)继承和重写
①定义一个父类形状,其中包括求形状面积的方法。继承该抽象类定义三角形,矩形,圆。分别创建一个三角形、矩形、圆,将各类图形的面积输出。
②形状转换为抽象类形状,求形状的面积定义为抽象方法。继承该抽象类定义三角形,矩形,圆。分别创建一个三角形、矩形、圆,将各类图形的面积输出,利用派生类构造抽象父类对象。
- 实验步骤
- 程序1
public class person{
private String id;
private String name;
public String food;
public String lc;
public person(String id ,String name,String food,String lc;){
this.id=id;
this.name=name;
this.food=food;
this.lc=lc;
}
public person(){
this.id="000";
this.name="张三";
this.food="饿了么";
this.walk="嘻嘻嘻";
}
public String get(){
return id;
}
public void set(String id){
this.id=id;
}
public String getname(){
return name;
}
public void setname(String name){
this.name=name;
}
public eat(){
return food;
}
public void set(String food){
this.food=food;}
public walk(){
return lc;}
public void set(String lc){
this.lc=lc;}
class student extends person{
public studentid;
public score;
- 程序2
abstract class Shape {
public abstract double getArea();
}
class Triangle extends Shape {
private double base;
private double height;
public Triangle(double base, double height) {
this.base = base;
this.height = height;
}
public double getArea() {
return 0.5 * base * height;
}
}
class Rectangle extends Shape {
private double width;
private double height;public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
public double getArea() {
return width * height;
}
}
class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double getArea() {
return Math.PI * radius * radius;
}
}public class Main {
public static void main(String[] args) {
Triangle triangle = new Triangle(5, 10);
Rectangle rectangle = new Rectangle(5, 10);
Circle circle = new Circle(5);
System.out.println("Triangle area: " + triangle.getArea());
System.out.println("Rectangle area: " + rectangle.getArea());
System.out.println("Circle area: " + circle.getArea());
}
}