码迷,mamicode.com
首页 > 其他好文 > 详细

内部类inner class

时间:2016-08-04 21:28:55      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:

1.什么是内部类,为什么要用内部类?

  可以将一个类定义在另一个类的定义内部,这就是内部类。

  当描述事物时,事物的内部还有事物,该事物用内部类来描述,因为内部事物在使用外部事物的内容。

如:

class Body{
         private class XinZang{//将这个内部类封装起来,对外界提供访问方式
                   void move(){}
             };
}

public woid show(){
         new XinZang().move();//调用其功能方法
}

2.内部类的访问规则

  (1)内部类可以直接访问外部类中的成员,包括私有

之所以可以直接访问,是因为内部类中持有了一个外部类的引用,格式:外部类名.this

  (2)外部类要访问内部类,必须要建立内部类的对象

  (3)在外部其他类中访问内部类的方式

    Outer.Inner in=new Outer().new Inner();
class Outer{//外部类
	private int x=3;
	class Inner{//内部类
		void function(){
			System.out.println("inner"+x);
		}
	}
	void method(){
		Inner in =new Inner();
		in.function();//要想访问内部类中的function方法,必须建立内部类对象
	}
}
class InnerClassDemo{//外部其他类
	public static void main(String[] args){
		Outer out=new Outer();
		out.method();
		//在外部其他类中访问内部类的方式
		Outer.Inner in=new Outer().new Inner();
		in.function();
	}
}

  (4)在外部其他类中,如何直接访问static内部类的非静态成员

    new Outer.Inner().function();

  (5)在外部其他类中,如何直接访问static内部类的静态成员

     Outer.Inner.function();

注意:如果一个内部类中定义了静态成员,那么该内部类必须是static

class Outer{//外部类
	private int x=3;
	static class Inner{//内部类中定义了静态方法,所以该内部类必须是static
		static void function(){
			System.out.println("inner"+x);
		}
	}

  外部类的静态方法访问内部类,该内部类也必须是static

class Outer{//外部类
	static class Inner{//内部类
		void show(){
			System.out.println("inner show");
		}
	}
	public static void method(){//外部类中的静态方法访问内部类,该内部类必须是static
		new Inner().show();
		
	}
}

  

 

内部类inner class

标签:

原文地址:http://www.cnblogs.com/GumpYan/p/5738253.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!