1、设计一个立方体类Cube,只有长边属性(side),具有设置边长(setSide),取得边长(getSide),计算表面积(superArea)和体积(volume)的方法。创建Cube对象,为其设置新边长,显示其边长,计算并显示其表面积和体积。
2、请按照以下要求设计一个学生类Student,并进行测试。 要求如下:
(1)Student类中包含姓名(name)、成绩(score)两个属性
(2)分别给这两个属性定义两个方法(setName和setScore),一个方法用于设置值,另一个方法用于获取值。
(3)Student类中定义一个无参的构造方法与一个接收两个参数的构造方法,两个参数分别为姓名与成绩属性赋值
(4)在测试类中创建两个Student对象,一个使用无参的构造方法,然后调用方法给姓名与成绩赋值,一个使用有参的构造方法,在构造方法中给姓名与成绩赋值。
实验内容1:
class Circle {
private double x;
private double y;
private double r;
public Circle(double x, double y, double r) {
this.x = x;
this.y = y;
this.r = r;
}
public void setX(double x) {
this.x = x;
}
public double getX() {
return x;
}
public void setY(double y) {
this.y = y;
}
public double getY() {
return y;
}
public void setRadius(double r) {
this.r = r;
}
public double getRadius() {
return r;
}
public double perimeter() {
return 2 * Math.PI * r;
}
public double area() {
return Math.PI * r * r;
}
}
class Cylinder extends Circle {
private double h;
public Cylinder(double x, double y, double r, double h) {
super(x, y, r);
this.h = h;
}
public void setHeight(double h) {
this.h = h;
}
public double getHeight() {
return h;
}
public double surfaceArea() {
double baseArea = super.area();
double circumference = super.perimeter();
return 2 * baseArea + circumference * h;
}
public double volume() {
double baseArea = super.area();
return baseArea * h;
}
}
public class Main {
public static void main(String[] args) {
Cylinder cylinder = new Cylinder(0, 0, 5, 10);
System.out.println("圆心坐标(x, y): " + cylinder.getX() + ", " + cylinder.getY());
System.out.println("圆的半径: " + cylinder.getRadius());
System.out.println("圆柱体的高度: " + cylinder.getHeight());
System.out.println("表面积: " + cylinder.surfaceArea());
System.out.println("体积: " + cylinder.volume());
}
}
实验内容2
class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public void show() {
System.out.println("姓名: " + name);
System.out.println("年龄: " + age);
}
}
class Undergraduate extends Student {
private String degree;
public Undergraduate(String name, int age, String degree) {
super(name, age);
this.degree = degree;
}
@Override
public void show() {
super.show();
System.out.println("学位: " + degree);
}
}
public class Main {
public static void main(String[] args) {
Student student = new Student("张三", 20);
student.show();
Undergraduate undergraduate = new Undergraduate("李四", 22, "本科");
undergraduate.show();
}
}
评论