⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 line.java

📁 《Java2程序设计实用教程(第2版)》课件
💻 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 + -