学习笔记 Java_ch04_内部类内部接口 2014.7.27

一、内部类和内部接口

1、直线类声明内嵌的点类和方向接口。代码:MyLineDemo.java
class Line
{
	private Point start, end;

	static interface Direction  //内部接口总是静态的
	{
		int LEFT = 0;
		int RIGHT = 1;
		int UP = 2;
		int DOWN = 3;
	}

	static class Point implements Direction  //为什么这里也要静态?
	{
		int x, y;

		Point()
		{
			this(0, 0);
		}

		Point(int x, int y)
		{
			this.x = x;
			this.y = y;
		}

		Point(Point p)
		{
			this(p.x, p.y);
		}

		public String toString()
		{
			return "(" + this.x + ", " + this.y + ")";
		}

		private Point another(int length, int direction)
		{
			Point p = new Point(this);
			switch(direction)
			{
				case LEFT: p.x -= length; break;  //Point类如果没有声明实现Direction接口,它必须通过Direction.LEFT才能引用常量
				case RIGHT: p.x += length; break;
				case UP: p.y += length; break;
				case DOWN: p.y -= length; break;
				default: p = null;
			}
			return p;
		}
	}

	Line(int x, int y, int length, int direction)
	{
		this.start = new Point(x, y);
		this.end = start.another(length, direction);
	}

	public String toString()
	{
		return "一条直线,起点为" + this.start.toString() + ", 终点为" + this.end.toString();
	}
}

class MyLineDemo
{
	public static void main(String[] args)
	{
		Line l = new Line(100, 100, 20, Line.Direction.LEFT);
		System.out.println(l);
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值