吉软-人文精英班-第七次作业

多态

package org.jsoft.polymorphism;

public  class Graph {
	  public  void show(){}
}


package org.jsoft.polymorphism;

public class Circular extends Graph{//圆
	private final int r=1;//半径
	public int getR() {
		return r;
	}
	public void show(){
		System.out.println("我是一个圆形,而且半径是:"+r);
	}
}


package org.jsoft.polymorphism;

public class Rectangular extends Graph{//矩形
	private final int height=3;//长
	private final int weight=2;//宽
	public int getHeight() {
		return height;
	}
	public int getWeight() {
		return weight;
	}
	public void show(){
		System.out.println("我是一个矩形,而且长和宽分别为:"+height+" "+weight);
	}
}


package org.jsoft.polymorphism;

public class Square extends Graph{//正方形
	private final int sideLenght=1;//边长
	public int getSideLenght() {
		return sideLenght;
	}
	public void show(){
		System.out.println("我是一个正方形,而且边长是:"+sideLenght);
	}
}


package org.jsoft.polymorphism;

import java.util.Scanner;

public class Test {
	public static void main(String[] args) {
		
		Scanner sc= new Scanner(System.in);
		while(true){
		System.out.println("输入0,1或2");
		int i=sc.nextInt();
		getShape(i).show();
		}
	}
	public static Graph getShape(int i){
		//如果i=0,返回一个半径为1的圆形
		//如果i=1,返回一个长为3,宽为2的矩形
		//如果i=2,返回一个边长为2的正方形
		if(i==0){
			 return new Circular();
		}
		else if(i==1){
			return new Rectangular();
		}
		else if(i==2){
			return new Square();
		}
		else return new Graph();
	}
}

运行的结果

转载于:https://my.oschina.net/u/3863623/blog/1821551

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值