《java入门第一季》之面向对象匿名内部类面试题

面试题一:

/*
        按照要求,补齐代码
            interface Inter { void show(); }
            class Outer { //补齐代码 }
            class OuterDemo {
                public static void main(String[] args) {
                      Outer.method().show();
                  }
            }
            要求在控制台输出”HelloWorld”
*/

interface Inter { 
	void show(); 
	//接口中的抽象方法,默认格式:public abstract
}

class Outer { 
	//补齐代码
	public static Inter method() {
		//子类对象 -- 子类匿名对象
		Inter i = new Inter() {//返回值类型是一个引用类型接口类型Inter
			public void show() {
				System.out.println("HelloWorld");
			}
		};
		return i;
		/*
		上面代码等价与下面:
		return new Inter(){
			public void show(){
				System.out.println("hello word!");
			}
		};
		*/
	}
}

class OuterDemo {
	public static void main(String[] args) {
		Outer.method().show();//返回一个对象。x.show();
		/*
			1:Outer.method()可以看出method()应该是Outer中的一个静态方法。
			2:Outer.method().show()可以看出method()方法的返回值是一个对象。因为show()应该被对象调用
				又由于接口Inter中有一个show()方法,所以我认为method()方法的返回值类型是一个接口。
		*/
	}
}



面试题二:

/*
    面试题:
        要求请填空分别输出30,20,10。
        
    注意:
        1:内部类和外部类没有继承关系。
        2:通过外部类名限定this对象
            Outer.this
*/

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) {

          填写代码。
    }    
}


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(Outer.this.num);
		}
	}
}
class InnerClassTest {
	public static void main(String[] args) {
		//外部类名.内部类名 对象名 = 外部类对象.内部类对象;
		Outer.Inner oi = new Outer().new Inner();
		oi.show();
	}	
}


原文地址:https://www.cnblogs.com/wanghang/p/6299841.html