码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2016-05-12 23:56:44      阅读:233      评论:0      收藏:0      [点我收藏+]

标签:

面试题一:

/*
        按照要求,补齐代码
            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();
	}	
}


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

标签:

原文地址:http://blog.csdn.net/qq_32059827/article/details/51346950

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