package org.jsoft.polymorphism;
public abstract class Shape {
//图形类
public abstract double area();//面积
public abstract double perimeter();//边长
public void show(){
System.out.println("面积为:"+this.area()+";边长为:"+this.perimeter());
}
}
package org.jsoft.polymorphism;
//圆
public class Circle extends Shape{
private int radius;//半径
public int getRadius() {
return radius;
}
public void setRadius(int radius) {
this.radius = radius;
}
public double perimeter(){
return 2*getRadius()*3.14;
}
public double area() {
return getRadius()*getRadius()*3.14;
}
public Circle(int radius) {
this.setRadius(radius);
}
}
package org.jsoft.polymorphism;
//矩形
public class Rectangle extends Shape{
private int length;//长
private int width;//宽
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public double area() {
return getLength()*getWidth();
}
public double perimeter() {
return 2*(getLength()+getWidth());
}
public Rectangle(int length, int width) {
this.setLength(length);
this.setWidth(width);
}
}
package org.jsoft.polymorphism;
//正方形
public class Square extends Shape{
private int borderLength;//边长
public int getBorderLength() {
return borderLength;
}
public void setBorderLength(int borderLength) {
this.borderLength = borderLength;
}
public double area() {
return getBorderLength()*getBorderLength();
}
public double perimeter() {
return 4*getBorderLength();
}
public Square(int borderLength) {
this.setBorderLength(borderLength);
}
}
package org.jsoft.polymorphism;
//测试类
public class TestShape {
public static void main(String[] args) {
TestShape t=new TestShape();
t.GetShape(0);
t.GetShape(1);
t.GetShape(2);
}
public void GetShape(int i) {
if(i==0) {
Circle c=new Circle(1);
System.out.print("这是一个圆形 半径为:"+c.getRadius()+" ");
c.show();
}
else if(i==1) {
Rectangle r=new Rectangle(2,1);
System.out.print("这是一个矩形 长为:"+r.getLength()+",宽为:"+r.getWidth()+" ");
r.show();
}
else if(i==2) {
Square s=new Square(2);
System.out.print("这是一个正方形 边长为:"+s.getBorderLength()+" ");
s.show();
}
}
}