面向对象-------内部类,成员内部类(二十八)

一.内部类概述和访问特点

* A:内部类概述

 在类中创建类.
* B:内部类访问特点
    * a:内部类可以直接访问外部类的成员,包括私有。
    * b:外部类要访问内部类的成员,必须创建对象。
    * 外部类名.内部类名 对象名 = 外部类对象.内部类对象;

class Demo1_InnerClass {
	public static void main(String[] args) {
		//Inner i = new Inner();
		//i.method();
		//外部类名.内部类名 = 外部类对象.内部类对象
		Outer.Inner oi = new Outer().new Inner();	//创建内部类对象
		oi.method();

	}
}

class Outer {
	private int num = 10;
	private class Inner {
		public void method() {
                        System.out.println("hello world!");
			System.out.println(num);
		}
	}
}

二.成员内部类私有使用

class Demo2_InnerClass {
	public static void main(String[] args) {
               /*
               这种方法行不通
               */
		//Outer.Inner oi = new Outer().new Inner();
		//oi.method();

		Outer o = new Outer();
		o.print();
	}
}

class Outer {
	private  int num = 10;
	private class Inner {
		public void method() {
			System.out.println(num);
		}
	}
       //成员内部类被私有了,只能用这种方法调用
	public void print() {
		Inner i = new Inner();
		i.method();
	}
}

三.静态成员内部类

成员内部类被静态修饰后的访问方式是:
    * 外部类名.内部类名 对象名 = 外部类名.内部类对象;

class Demo1_InnerClass {
	public static void main(String[] args) {
		//外部类名.内部类名 对象名 = 外部类名.内部类对象;
		Outer.Inner oi = new Outer.Inner();
		oi.method();
		//内部类里面静态方法的访问特点:外部类.内部类.静态方法名();
		Outer.Inner2.print();
	}
}

class Outer {
	static class Inner {
		public void method() {
			System.out.println("method");
		}
	}

	static class Inner2 {
		public static void print() {
			System.out.println("print");
		}
	}
}

四.成员内部类的面试题

* A:面试题
*
        要求:使用已知的变量,在控制台输出30,20,10。
        
        class Outer {
            public int num = 10;
            class Inner {
                public int num = 20;
                public void show() {
                    int num = 30;
                    System.out.println(?);
                    System.out.println(??);
                    System.out.println(???);
                }
            }
        }
        class InnerClassTest {
            public static void main(String[] args) {
                Outer.Inner oi = new Outer().new Inner();
                oi.show();
            }    
        }

 

class Test1_InnerClass {
	public static void main(String[] args) {
		Outer.Inner oi = new Outer().new Inner();
		oi.show();
	}
}
//内部类之所以能获取到外部类的成员,是因为他能获取到外部类的引用外部类名.this
class Outer {
	public int num = 10;
	class Inner {
		public int num = 20;
		public void show() {
			int num = 30;
			System.out.println(num);
			System.out.println(this.num);
			//System.out.println(new Outer().num); //使用对象来访问成员变量
			System.out.println(Outer.this.num);
		}
	}
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值