前言
涉及知识点
- 1.对于创建对象和类的初步实践;
如构建圆类和矩形类; - 1.对于抽象类和继承与多态的认识;
如构建shape类;
题量
- 不多,可以完成。
难度
- 不大,可以完成。
设计与分析
题目源码如下
import java.util.*;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int choice = input.nextInt();
switch (choice) {
case 1://Circle
double r = input.nextDouble();
Shape circle = new Circle(r);
circle.getArea();
break;
case 2://Rectangle
double x1 = input.nextDouble();
double y1 = input.nextDouble();
double x2 = input.nextDouble();
double y2 = input.nextDouble();
Point leftTopPoint = new Point(x1, y1);
Point lowerRightPoint = new Point(x2, y2);
Rectangle rectangle = new Rectangle(leftTopPoint, lowerRightPoint);
rectangle.getArea();
break;
}
}
}
public abstract class Shape {
public abstract void getArea();
}
```plaintext
public class Circle extends Shape {
double r;
public Circle(double r){
this.r=r;
}
@Override
public void getArea(){
double s = (3.1415926)*r*r;
System.out.printf("%.2f",s);
}
}
public class Rectangle extends Shape {
private Point topLeftPoint;
private Point lowerRightPoint;
public Rectangle(Point topLeftPoint,Point lowerRightPoint){
this.lowerRightPoint=lowerRightPoint;
this.topLeftPoint=topLeftPoint;
}
@Override
public void getArea(){
double s=(topLeftPoint.getX() - lowerRightPoint.getX())*(topLeftPoint.getY()- lowerRightPoint.getY());
if(s<0){
s=-s;
}
System.out.printf("%.2f",s);
}
}
public class Point {
private double x;
private double y;
public Point(){
}
public Point(double x,double y){
this.x=x;
this.y=y;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
}