内部类
内部类:在一个类的内部嵌套其它类的操作叫内部类。
简单的内部类:
public class Outer {
private String msg = "hello world";
class Inner //定义一个内部类
{
public void print()
{
System.out.println(msg);
}
}
public void func()
{
Inner inner = new Inner();
inner.print();
}
}
public class MainTest {
public static void main(String[] args) {
Outer outer = new Outer();
outer.func();
}
}
引入内部类之后我们牺牲了程序的规范性,代码有些混乱。但是换来的却是内部类可以方便的操作外部类的私有属性。
针对上面的代码,我们可以修改为:
public class Outer {
private String msg = "hello world";
public String getMsg()
{
return this.msg;
}
public void func()
{
Inner inner = new Inner(this);
//this表示当前类的对象,类似C++拷贝构造时return的this
inner.print();
}
}
public class Inner {
Outer out = new Outer();
public Inner(Outer out) //引用传递this.out = main.out
{
this.out = out;
}
public void print()
{
System.out.println(out.getMsg());
}
}
public class MainTest {
public static void main(String[] args) {
Outer outer = new Outer();
outer.func();
}
}
- 内部类的访问只有通过外部类才可以完成。
- 如果一个内部类只想被外部类使用,可以使用private关键字。
- 进行属性访问时必须加上this。
static修饰内部类
内部类使用了static修饰,该内部类只允许访问外部类的static部分。
该内部类实例化的语句是:
外部类.内部类 内部类对象 = new 外部类.内部类();
eg:
public class Outer2 {
private static String msg = "hello world";
static class Inner
{
public void print()
{
System.out.println(msg);
}
}
public void func()
{
Inner in = new Inner();
in.print();
}
}
public class TestMain {
public static void main(String[] args) {
Outer2.Inner in = new Outer2.Inner();
in.print();
}
}
在方法中定义内部类
public class Outer3 {
private static String msg = "hello world";
public void func(int num)
{
class Inner
{
public void print()
{
System.out.println("num: " + num);
System.out.println("msg: " + msg);
}
}
new Inner().print();
}
}
public class TestMain {
public static void main(String[] args) {
Outer3 out = new Outer3();
out.func(33);
}
}
内部类的特点:
- 破坏了程序的结构。
- 方便进行私有属性的访问。(外部类也可以访问内部类的私有域)
- 如果发现类名称上出现了"." ,应当立即想到内部类的概念。
暂时不推荐使用!
我想一直陪着你,小马同学。万事如意~