Java作业-多态

171257_sHIl_3417964.png

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();
	        }
	    
	}
}

 

转载于:https://my.oschina.net/u/3417964/blog/1822691

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值