标签:java
这一章节我们来讨论一下内部类。
1.概念
在类的内部创建的类就是内部类。
package com.ray.ch08;
public class Test {
class Destination {
}
class Content {
}
}2.为什么需要内部类?
(1)隐藏代码
package com.ray.ch08;
import com.ray.ch08.Test.Destination;
public class Test {
class Destination {
}
private class Content {
}
}
class Ship {
// Content content = new Test().new Content();//error
}当我们需要调用某个类的内部类时,必须先new 外部类,就像下面的Destination类一样。
package com.ray.ch08;
import com.ray.ch08.Test.Destination;
public class Test {
class Destination {
}
private class Content {
}
}
class Ship {
Destination destination = new Test().new Destination();
// Content content = new Test().new Content();//error
}(2)通过与外部类的通信
package com.ray.ch08;
public class Test {
private int id = 0;
class Destination {
private void print() {
System.out.println(id);// 这里的id是int com.ray.ch08.Test.id
}
}
private class Content {
}
}
(3)代码更加优雅
这一点就不用代码演示,因为根据不同的需求要求各不相同。
总结:这一章节主要讲述了内部类的概念与使用的原因。
这一章节就到这里,谢谢。
-----------------------------------
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:java
原文地址:http://blog.csdn.net/raylee2007/article/details/49765265