内部类

内部类的访问规则:

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

         之所以可以直接访问外部类的成员,是因为内部类中持有了一个外部类的引用,(外部类名 . this . +...)   Outer.this.

2:外部类要访问内部类,必须创建内部对象;

 

 

访问格式:

1,当内部类定义子在外部类的的成员位置上,而且非私有,可以在外部其他类中,

可以直接建立内部类对象。

格式

    外部类名 . 内部类名    变量名 =外部类对象 . 内部类对象

   Outer.Inner p=new Outer().new Inner();

2,当内部类在成员位置上,就可以被成员修饰符修饰。

  比如,private:件内部类在外部类中进行封装

         static:内部具备static的特性;

      当内部类被static修饰后,只能直接访问外部类中的静态成员,出现了访问据局限

 

       在外部其他类中如何直接访问内部非静态类呢??

         new Outer.Inner().function();

 

        在外部其他类中如何直接访问内部静态类呢??

         Outer.Inner.function();

 

注意:
当内部类中定义了静态成员,该内部类必须是静态的;

当外部类的静态方法访问内部类时,内部类也需要静态;

 

 

 

class Outer
{
	private int x=3;
	class Inner
	{
		void function()
		{
		System.out.println("inter..."+x);
	     }
	}
	void method()
	{
		Inner in=new Inner();
		in.function();
	}

}
class NeiDemo
{
	public static void main(String[] args)
    {
		Outer p=new Outer();
		p.method();
	}
}

 

看下面代码

class Outer
{
	private int x=3;
	class Inner
	{
		int x=4;
		void function()
		{
			int x=5;
		System.out.println("inter..."+x);
	     }
	}
	void method()
	{
		Inner in=new Inner();
		in.function();
	}

}///下面主函数省略了


1.如果这样打印结果是   5;

2 . 代码System.out.println("inter..."+this.x);打印为4;

3.那如果想打印 3 呢??

System.out.println("inter..."+Outer.this.x);

 

那如果想直接从主函数调用内部类中方法呢,并且不创建内部对象;

class Outer
{
	private int x=3;
	class Inner
	{
		void function()
		{
		System.out.println("inner..."+x);
	     }
	}

}
class NeiDemo
{
	public static void main(String[] args)
    {
		Outer.Inner p=new Outer().new Inner();
		p.function();
	}
}

 

 

下面看几个静态的情况:
1:

class Outer
{
	private static int x=3;
	static class Inner
	{
		void function()
		{
		System.out.println("inner..."+x);
	     }
	}

}
class NeiDemo
{
	public static void main(String[] args)
    {
		new Outer.Inner().function();
	}
}

outer一加载 就自动加载inner,就不需要创建outer的对象,但function不是静态的,所以要创建inner的对象去调用,至于前面为什么这么写,格式问题;

 

2.


 

class Outer
{
	private static int x=3;
	static class Inner
	{
		static void function()
		{
		System.out.println("inner..."+x);
	     }
	}

}
class NeiDemo
{
	public static void main(String[] args)
    {
		Outer.Inner.function();
	}
}


这个跟上面的区别在于functio是静态的,不要创建inner对象;

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值