Shape类:父类,抽象类
public abstract class Shape {
private String name;//保存各个图形的名称
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
abstract String display();//抽象方法显示图形信息
}
Circle类:圆类
public class Circle extends Shape{
private double radius;//半径
private double x;//圆心x坐标
private double y;//圆心y坐标
public Circle(double radius,double x,double y){
this.radius=radius;
this.x=x;
this.y=y;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
@Override
String display() {//重写抽象方法,输出圆的信息
// TODO Auto-generated method stub
return getName()+"的半径为:"+getRadius();
}
}
Rectangle类:矩形类
public class Rectangle extends Shape{
private double width;//矩形的长
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
public double getLength() {
return length;
}
public void setLength(double length) {
this.length = length;
}
private double length;//矩形的宽
public Rectangle(double width,double length){
this.width=width;
this.length=length;
}
@Override
String display() {//重写抽象方法,输出信息
// TODO Auto-generated method stub
return getName()+"的长为:"+getWidth()+",宽为:"+getWidth();
}
}
Square类:正方形类
public class Square extends Shape{
private double length;//正方形边长
public double getLength() {
return length;
}
public void setLength(double length) {
this.length = length;
}
public Square(double length){
this.length=length;
}
@Override
String display() {//重写抽象方法,输出信息
// TODO Auto-generated method stub
return getName()+"的边长为:"+getLength();
}
}
Testshape类:测试类
public class TestShape {
public static Shape getShape(int i){//题目要求的getShape方法,返回值是类,返回值的类型和i有关
Shape s1 = new Circle(1,0,0);
Shape s2 = new Rectangle(3,2);
Shape s3 = new Square(2);
if(i==0){
s1.setName("圆");
return s1;
}
else if(i==1){
s2.setName("矩形");
return s2;
}
else if(i==2){
s3.setName("正方形");
return s3;
}
else //else if最后一定要有else吗
return null;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入i值(0~2):");
int i=sc.nextInt();
System.out.println(TestShape.getShape(i).display());//这里display实现多态
}
}