
题目1: 编写一个抽象类Shape,声明计算图形面积的抽象方法。再分别定义Shape的子类Circle(圆)和Rectangle(矩形),在两个子类中按照不同图形的面积计算公式,实现Shape类中计算面积的方法。
abstract class Shape {
public abstract double getArea();
}
class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double getArea() {
return Math.PI * radius * radius;
}
}
!!!不要照抄!!!
!!!不要照抄!!!
!!!不要照抄!!!
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;
}
}
!!!这里的ShapeTest是保存的文件名,自行修改!!!
public class ShapeTest {
public static void main(String[] args) {
!!!下面的半径长宽自行修改,输入和输出的都要改!!!
Circle circle = new Circle(4);
System.out.println("圆的半径:4,圆面积:" + circle.getArea());
Rectangle rect = new Rectangle(4, 6);
System.out.println("长:4,宽:6的矩形面积:" + rect.getArea());
}
}
题目2: 创建一个接口IShape,接口中有一个求取面积的抽象方法public double area()。定义一个正方形类Square,该类实现了IShape接口。Square类中有一个属性表示正方形的边长;在构造方法中初始化该边长。定义一个主类,在主类中创建类的实例对象,求该类正方形对象的面积。
interface IShape {
double area();
}
class Square implements IShape {
double sideLength;
public Square(double sideLength) {
this.sideLength = sideLength;
}
public double area() {
return sideLength * sideLength;
}
}
!!!不要照抄!!!
!!!不要照抄!!!
!!!不要照抄!!!
!!!下面的is是我保存的文件名,自己修改!!!
public class is {
public static void main(String args[]) {
!!!自行修改下面的边长!!!
IShape shape = new Square(6);
System.out.println(shape.area());
}
}
