2016/3/10 Java 错题

1.

What is the result of compiling and executing the following fragment of code:

1 Boolean flag = false;
2 if (flag = true)
3 {
4     System.out.println(“true”);
5 }
6 else
7 {
8     System.out.println(“false”);
9 }

Ans:  The text“true” is displayed.

解析:Boolean修饰的变量为包装类型,初始化值为false,进行赋值时会调用Boolean.valueOf(boolean b)方法自动拆箱为基本数据类型,因此赋值后flag值为true,输出文本true。 如果使用==比较,则输出文本false。if的语句比较,除boolean外的其他类型都不能使用赋值语句,否则会提示无法转成布尔值。

 

2.判断对错。在java的多态调用中,new的是哪一个类就是调用的哪个类的方法。

Ans:false
解析:
java多态有两种情况:重载和覆写
在覆写中,运用的是动态单分配,是根据new的类型确定对象,从而确定调用的方法;
在重载中,运用的是静态多分派,即根据静态类型确定对象,因此不是根据new的类型确定调用的方法
 
3.java中下面哪些是Object类的方法()

notify()
notifyAll()
sleep
wait()

Ans:ABD

解析:在根类Object中包含一下方法: 

clone();
equals();
finalize();
getClass();
notify(),notifyAll();
hashCode();
toString();
wait()

4.
已知如下类定义:

 1 class Base {  
 2  public Base (){ 
 3  //... 
 4  }  
 5  public Base ( int m ){ 
 6  //... 
 7  }  
 8  public void fun( int n ){ 
 9  //... 
10  } 
11 }  
12 public class Child extends Base{  
13  // member methods  
14 }  

如下哪句可以正确地加入子类中?

private void fun( int n ){ //...}
void fun ( int n ){ //... }
protected void fun ( int n ) { //... }
public void fun ( int n ) { //... }

Ans:D

解析:

Cannot reduce the visibility of the inherited method from Base
意思就是告诉你:不能降低从基类继承的方法的可见性。
那么,为什么不能降低可见性呢?
因为,每个子类的实例都应该是一个基类的有效实例,如果降低了方法的可见性,那么就相当于子类失去了一个父类的方法,这个时候,父类将不是一个有效的基类。
posted @ 2016-03-10 18:33  Run_dream  阅读(357)  评论(0编辑  收藏  举报