这些都是在平时的面试或者什么时候会出现的小问题陷阱,再次做下记录和大家共勉
1)
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
packageWangyi;classBase{ publicvoidmethod() { System.out.println("Base"); } }classSon extendsBase{ publicvoidmethod() { System.out.println("Son"); } publicvoidmethodB() { System.out.println("SonB"); }}publicclassTest01{ publicstaticvoid
main(String[] args) { Base
base = newSon(); base.method(); base.methodB(); }} |
问这个程序的输出结果。
正确答案: D 你的答案: C (错误)
Base SonB
Son SonB
Base Son SonB
编译不通过
解析:
下面这道题,我在分析的时候,已经想到了在new多态的时候,需要小心(需要注意多态是需要条件的:比如:必须extends和重写父类方法)
但是没有注意到:父类的引用无法访问子类独有的方法
2)
有如下4条语句:()
|
1
2
3
4
|
Integer
i01=59;inti02=59;Integer
i03=Integer.valueOf(59);Integer
i04=newInteger(59); |
以下输出结果为false的是:
正确答案: C 你的答案: D (错误)
System.out.println(i01==i02);
System.out.println(i01==i03);
System.out.println(i03==i04);
System.out.println(i02==i04);
解析:
在分析这道题的时候确实是在CD两个选项之间犹豫,当时已经忘记什么装箱拆箱之类的概念了
下面分析一下这道题目了
A:Integer i01 = 59. 直接赋值数字,java会自动装箱,自动调用Integer.valueOf(59).
B:int和integer(无论new否)比,都为true,因为会把Integer自动拆箱为int再去比
C:整数类型在-128~127之间时,会使用缓存,造成的效果就是,如果已经创建了一个相同的整数,使用valueOf创建第二次时,不会使用new关键字,而用已经缓存的对象。所以使用valueOf方法创建两次对象,若对应的数值相同,且数值在-128~127之间时,两个对象都指向同一个地址。
3)
1226

被折叠的 条评论
为什么被折叠?



