1.Shape类(父类)
public class Shape{
private int x;
private int y;
public Shape(){
}
public Shape(int x,int y){
setX(x);
setY(y)
}
public int getX(){
return x;
}
public void setX(int x){
this.x=x;
}
public int getY(){
return y;
}
public void setY(int y){
this.y=y;
}
public void show(){
System.out.println("横坐标:"+getX()+",纵坐标:"+getY());
}
}
2.Circle类(子类)
public class Cirle extends Shape{
private int r;
public Circle(){
super();
}
public Circle(int x,int y,int r){
super(x,y);
setR(r);
}
public int getR(){
return r;
}
public void setR(int r){
if (r>0){
this.r=r;
}else{
System.out.println("半径不合理");
}
}
@override
public void show(){
super.show();
System.out.println("半径:"+getR());
}
}
3.Rect类(子类)
public class Rect extends Shape{
private int len;
private int wid;
public Rect(){
super();
}
public Rect(int x, int y,int len,int wid) {
super(x, y);
setLen(len);
setWid(wid);
}
public int getLen() {
return len;
}
public void setLen(int len) {
if(len>0)
this.len = len;
else
System.out.println("长度不合理!!");
}
public int getWid() {
return wid;
}
public void setWid(int wid) {
if(wid>0)
this.wid = wid;
else
System.out.println("宽度不合理!!");
}
@Override
public void show(){
super.show();
System.out.println("长度:"+getLen()+",宽度:"+getWid());
}
}
4.TestShape类(测试类)
public class TestShape(){
//自定义成员方法根据参数传入的对象既能打印矩形又能打印圆形
public static void drew(Shape s){
s.show()
}
public static void main(String[] args){
TestShape.draw(new Rect(1,2,3,4));
TestShape.draw(new Circle(1,1,1));
System.out.println("----------");
Shape[] sarr = new Shape[5];
sarr[0] = new Rect(1,2,3,4);
sarr[1] = new Circle(1,2,3);
sarr[2] = new Rect(1,2,3,4);
sarr[3] = new Rect(1,2,3,4);
sarr[4] = new Rect(1,2,3,4);
sarr[0].show();
TestShape.draw(sarr[1]);
}
}
多态的使用场合:
1.在方法体中使用父类的引用指向子类对象的方法形成多态;
Account acc = new FixedAccount(1000);
2. 在方法的参数传递过程中形成多态;
public static void test(Person p){…}
test(new Worker(“zhang”,30,3000));
3.通过方法的返回值类型形成多态。
Calendar getInstance(){
return createCalendar(TimeZone.getDefault(), Locale.getDefault(Locale.Category.FORMAT));
}