the journey is the reward...

常用链接

统计

最新评论

你能通过下面的3道java面试题吗?

1.java static inner class 和 non-static inner class的区别?  

2.请写出一个singleton模式的class.

你如果写出下面的2种样式,我会问你:请问你如何在同一个jvm中并且在同一个classLoader中得到它的多个实例?(请不要奇怪)

样列1:

public class Singleton {  
 private final static Singleton instance=new Singleton();
 private Singleton(){} 
 public static Singleton newInstance(){  
  return instance;  
 } 
}

样列2:

public class Singleton { 
 private static volatile int instanceCounter=0; 
 private Singleton(){
  if(instanceCounter>0)
   throw new RuntimeException("can't create multi instances!");
  instanceCounter++;
 }
 
 private final static Singleton instance=new Singleton();
 public static Singleton newInstance(){  
  return instance;  
 }

3.java 的exception 分checked,unchecked.像RuntimeException,Error都不用显式try-catch,直接可以throw,

但是一般的exception是必须catch的:

throw new Exception("..."),如果这句不在try-catch体内,或者方法的声明没有throws,那么编译是通不过的.

ok,请看如下的代码:

public class TestClass { 
 
 public void  testMethod()/*这里没有throws 哦!*/{  

          ......
           throw new Exception("force throw the exception...");
          ......
 }
}

很明显上面的方法如果这样的话是通不过编译的,但是如果非得要你在testMethod体中在运行时throw一个很一般的Exception,请问你有办法吗? 

这3道题可不是sun出的考题哦!不信你搜搜......

posted on 2010-03-03 11:28 adapterofcoms 阅读(926) 评论(4)  编辑  收藏 所属分类: java bbs

评论

# re: 你能通过下面的3道java面试题吗? 2010-07-29 09:39 epinszteinic

静态内部类和非静态内部类:
new的方法不一样。
非静态内部类依赖于父亲的实例,不允许有静态成员。

直接上代码:

public class TestAA {

public static void main(String[] args) {

new TestAA().new A();
new TestAA.B();

new TestAA().testMethod();
}

class A {
public A() {
System.out.println("A");
}
}

static class B {
public B() {
System.out.println("B");
}
}

public void testMethod() {
throw new RuntimeException(new Exception("一般的Exception"));
}

}
  回复  更多评论   

# re: 你能通过下面的3道java面试题吗? 2011-01-20 02:44 lin

第三题就创建一个对象,在对象中抛出异常就得了呀  回复  更多评论   

# re: 你能通过下面的3道java面试题吗? 2011-04-28 10:35 郑思毕

第三个问题好无聊啊,实际运用中,根本不可能有这样的事情,明显违反了的规则,为何还要强求  回复  更多评论   

# re: 你能通过下面的3道java面试题吗? 2012-04-07 22:38 Daniel Hu

用ThreadLocal  回复  更多评论   


只有注册用户登录后才能发表评论。


网站导航: