?? line.java
字號:
//【例4.4】 設計點的坐標作為直線類的內部類。
public class Line //直線類,外部類
{
protected Point p1,p2; //直線的起點和終點
protected class Point implements Direction
{ //點類,內部類,實現方向接口
protected int x,y; //點的坐標,內部類的成員變量
protected Point(int x,int y) //內部類的構造方法
{
this.x = x;
this.y = y;
}
protected Point()
{
this(0,0);
}
protected Point(Point p)
{
this(p.x, p.y);
}
protected String toStr() //內部類的成員方法
{
return "("+this.x+","+this.y+")";
}
protected Point another(int interval,int direction)
{ //以當前點為基點,返回給定距離和方向的另一個點對象
Point p2 = new Point(this);
switch (direction)
{
case LEFT: //Direction.LEFT
{
p2.y -= interval;
break;
}
case RIGHT: //Direction.RIGHT
{
p2.y += interval;
break;
}
case UP: //Direction.UP
{
p2.x -= interval;
break;
}
case DOWN: //Direction.DOWN
{
p2.x += interval;
break;
}
default:
p2 = null;
}
return p2;
}
} //內部類結束
public Line(Point p1,int length,int direction) //直線類的構造方法
{ //參數指定直線的起點、長度和方向
this.p1 = p1;
this.p2 = p1.another(length,direction); //外部類調用內部類的成員方法
}
public Line(int x,int y,int length,int direction)
{
this.p1 = new Point(x,y); //外部類創建內部類對象
this.p2 = this.p1.another(length,direction);
}
public Line()
{
this(0,0,1,0);
}
public void print() //直線類的成員方法
{
System.out.println("一條直線,起點為"+this.p1.toStr()+",終點為"+this.p2.toStr());
}
public static void main(String args[])
{
Line line1 = new Line(100,100,20,Direction.LEFT);
line1.print();
}
}
/*
程序運行結果如下:
一條直線,起點為(100,100),終點為(100,120)
*/
/*
程序正確:
1、類與類中成員可以同名
public class Line //直線類,外部類
{
public int Line; //類與類中成員同名
}
*/
/*
程序錯誤:
1、外部類與內部類不能同名
public class Line //直線類,外部類
{
protected class Line //編譯錯,Line is already defined in unnamed package
{
}
}
*/
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -