close
多型:父參考控制子物件
,呼叫子物件的函數
1. Main
public class Main
{
public static void main(String[] args)
{ // TODO Auto-generated constructor stub
Shape sh=new Cone();
sh.draw();
System.out.println("-----------------------------");
Cone c=new Cone(1,1,10,2,2,3,3);
c.draw();
System.out.println("-----------------------------");
c.setX2(200);
c.setY2(200);
c.draw();
}
}
2.Shape
public class Shape
{
private int x;
private int y;
public Shape()
{
x=0;
y=0;
}
public Shape(int x,int y)
{
this.x=x;
this.y=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 draw()
{
System.out.println("x=" +x+ ",y" +y);
}
}
3 Circle
public class Circle extends Shape
{
private int radius;
public Circle()
{
radius=0;
}
public Circle(int x,int y,int radius)
{
super(x,y);
this.radius=radius;
}
public int getRadius()
{
return radius;
}
public void setRadius(int radius)
{
this.radius = radius;
}
public void draw()
{
super.draw();
System.out.println("radius="+radius);
}
}
4 Cone
public class Cone extends Circle
{
private int x2;
private int y2;
private int x3;
private int y3;
public Cone()
{
// TODO Auto-generated constructor stub
this.x2=0;
this.y2=0;
this.x3=0;
this.y3=0;
}
public Cone(int x,int y,int radius,int x2,int y2,int x3,int y3)
{
super(x,y,radius);
this.x2=x2;
this.y2=y2;
this.x3=x3;
this.y3=y3;
}
public int getX2()
{
return x2;
}
public void setX2(int x2)
{
this.x2 = x2;
}
public int getY2()
{
return y2;
}
public void setY2(int y2)
{
this.y2 = y2;
}
public int getX3()
{
return x3;
}
public void setX3(int x3)
{
this.x3 = x3;
}
public int getY3()
{
return y3;
}
public void setY3(int y3)
{
this.y3 = y3;
}
public void draw()
{
super.draw();
System.out.println("x2= " +x2+ " ,y2=" + y2);
System.out.println("x3= " +x3+ " ,y3=" + y3);
}
}
5. result
x=0,y0
radius=0
x2= 0 ,y2=0
x3= 0 ,y3=0
-----------------------------
x=1,y1
radius=10
x2= 2 ,y2=2
x3= 3 ,y3=3
-----------------------------
x=1,y1
radius=10
x2= 200 ,y2=200
x3= 3 ,y3=3
文章標籤
全站熱搜
留言列表