`
ze_nana
  • 浏览: 48091 次
社区版块
存档分类
最新评论

内部类

 
阅读更多

一个类定义在一个类的里面;

内部类可以随意使用外部类的成员;

要生成内部类对象,要先生成外部类对象;new一个外部类的对象.new一个内部类的对象;


外部类A,内部类B

A a=new A(); 生成外部类对象

A.B b= a.new B(); 生成内部类对象

 

//方向接口
public interface Direction
{
	public static final int LEFT=0;
	public static final int RIGHT=1;
	public static final int UP=2;
	public static final int DOWN=3;
}
 

 

 

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:
			{
				p2.x-=interval;
				break;
			}
			case RIGHT:
			{
				p2.x+=interval;
				break;
			}
			case UP:
			{
				p2.y+=interval;
				break;
			}
			case DOWN:
			{
				p2.y-=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,0,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.RIGHT);
		line1.print();
	}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics