3.1.设计一个Calculable接口和它的实现类Shape以及Shape的子类Square和Circle。要求如下: (1)Calculable接口中有一个抽象方法calArea(),方法无参数,返回一个double类型的结果。 (2)Shape类作为抽象类定义,有一个name成员变量 (3)Square和Circle重写父类中的方法calArea() (4)编写应用程序,创建Square和Circle对象,计算边长为2的正方形的面积和半径为3的圆形面积。 3.2学校中有老师和学生两类人,而在职研究生既是老师又是学生,对学生的管理和对教师的管理在他们身上都有体现。
时间: 2023-06-14 12:07:35 浏览: 132
3.1.
```java
public interface Calculable {
double calArea();
}
public abstract class Shape {
protected String name;
}
public class Square extends Shape implements Calculable {
private double length;
public Square(double length) {
this.name = "正方形";
this.length = length;
}
@Override
public double calArea() {
return length * length;
}
}
public class Circle extends Shape implements Calculable {
private double radius;
public Circle(double radius) {
this.name = "圆形";
this.radius = radius;
}
@Override
public double calArea() {
return Math.PI * radius * radius;
}
}
public class Main {
public static void main(String[] args) {
Square square = new Square(2);
System.out.println(square.name + "的面积为:" + square.calArea());
Circle circle = new Circle(3);
System.out.println(circle.name + "的面积为:" + circle.calArea());
}
}
```
输出结果为:
```
正方形的面积为:4.0
圆形的面积为:28.274333882308138
```
3.2.
```java
public abstract class Person {
protected String name;
public Person(String name) {
this.name = name;
}
public abstract void work();
}
public class Teacher extends Person {
public Teacher(String name) {
super(name);
}
@Override
public void work() {
System.out.println(name + "老师正在教课");
}
}
public class Student extends Person {
public Student(String name) {
super(name);
}
@Override
public void work() {
System.out.println(name + "学生正在学习");
}
}
public class GraduateStudent extends Person {
public GraduateStudent(String name) {
super(name);
}
@Override
public void work() {
System.out.println(name + "研究生正在教课和学习");
}
}
public class Main {
public static void main(String[] args) {
Person teacher = new Teacher("张三");
teacher.work();
Person student = new Student("李四");
student.work();
Person graduateStudent = new GraduateStudent("王五");
graduateStudent.work();
}
}
```
输出结果为:
```
张三老师正在教课
李四学生正在学习
王五研究生正在教课和学习
```
阅读全文