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