`
李灵晖-raylee
  • 浏览: 128554 次
博客专栏
Group-logo
从头认识java
浏览量:0
文章分类
社区版块
存档分类
最新评论

从头认识java-8.4 内部类与向上转型

 
阅读更多

这一章节我们来讨论一下内部类与向上转型。

跟普通的类一样,内部类也可以实现某个接口然后向上转型。

为什么?

因为这样能够更好的隐藏实现的细节,基本其他程序员使用继承来扩展接口和方法都不能访问相关实现。

package com.ray.ch03;

public class Test {
	private class Person implements CanRun {

		@Override
		public void run() {
			System.out.println("run");
		}
	}

	public Person getPerson() {
		return new Person();
	}

	public static void main(String[] args) {
		CanRun person = new Test().getPerson();
		person.run();
	}
}

interface CanRun {
	void run();
}

上面的代码通过了接口,完全隔绝了实现与接口的依赖,完全隐藏了实现的细节。

上面的代码即便我通过继承Test来扩展,但是由于Test所有的实现方法都是private的,因此,是不会有任何重写的方法。

package com.ray.ch03;

public class Test {
	private class Person implements CanRun {

		@Override
		public void run() {
			System.out.println("run");
		}
	}

	public Person getPerson() {
		return new Person();
	}

	public static void main(String[] args) {
		CanRun person = new Test().getPerson();
		person.run();
	}
}

class myTest extends Test {
	//没有任何需要重写的方法
}

interface CanRun {
	void run();
}

我们再来看一个例子:

package com.ray.ch03;

public class Test {
	private class Ship implements Destination {
		private String destination = "abc";

		@Override
		public String read() {
			return destination;
		}
	}

	public Ship destination() {
		return new Ship();
	}

	public static void main(String[] args) {
		Destination destination = new Test().destination();
		destination.read();
	}
}

class myTest extends Test {
	// 没有任何需要重写的方法
}

interface Destination {
	String read();
}


总结:这一章节主要讨论了内部类与向上转型,通过接口把实现完全隐藏起来。


这一章节就到这里,谢谢。

-----------------------------------

目录


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics