错题726-java

01
class
Car extends Vehicle { public static void main (String[] args) { new Car(). run(); } private final void run() { System. out. println ("Car"); } } class Vehicle { private final void run() { System. out. println("Vehicle"); } }

下列哪些针对代码运行结果的描述是正确的?

A.Car
B.Vehicle
C.Compiler error at line 3
D.Compiler error at line 5
E.Exception thrown at runtime
解析 :选A。
此题的父类方法有private修饰,所以对子类不可见,子类不能覆盖。所以子类方法和父类是两个方法。
扩展:如果父类方法将private改为public 会怎样?
        会报错,因为父类方法有final修饰,不能被覆盖。
 
2.What is the result of compiling and executing the following fragment of code:
Boolean flag = false;
if (flag = true)
{
    System.out.println(“true”);
}
else
{
    System.out.println(“false”);
}
A:The code fails to compile at the “if” statement.
B:An exception is thrown at run-time at the “if” statement.
C:The text“true” is displayed.
D:The text“false”is displayed.
E;Nothing is displayed.
答案:正确答案: C   你的答案: A (错误)
解析:Boolean修饰的变量为包装类型,初始化值为false,进行赋值时会调用Boolean.valueOf(boolean b)方法自动拆箱为基本数据类型,因此赋值后flag值为true,输出文本true。
如果使用==比较,则输出文本false。if的语句比较,除boolean外的其他类型都不能使用赋值语句,否则会提示无法转成布尔值。


3.如何获取ServletContext设置的参数值?
A:context.getParameter()
B:context.getInitParameter()
C:context.getAttribute()
D:context.getRequestDispatcher()
答案:正确答案: B   你的答案: C (错误)
解析:
getParameter()是获取POST/GET传递的参数值;
getInitParameter获取Tomcat的server.xml中设置Context的初始化参数
getAttribute()是获取对象容器中的数据值;
getRequestDispatcher是请求转发。
 
4.在java中重写方法应遵循规则的包括()
A:访问修饰符的限制一定要大于被重写方法的访问修饰符
B;可以有不同的访问修饰符
C:参数列表必须完全与被重写的方法相同
D:必须具有不同的参数列表
答案:正确答案: B C   你的答案: A C (错误)
解析:
(1) 父类与子类之间的多态性,对父类的函数进行重新定义。如果在子类中定义某方法与其父类有相同的名称和参数,我们说该方法被重写 (Overriding)。在Java中,子类可继承父类中的方法,而不需要重新编写相同的方法。
 
但有时子类并不想原封不动地继承父类的方法,而是想作一定的修改,这就需要采用方法的重写。
 
方法重写又称方法覆盖。
 
 
    (2)若子类中的方法与父类中的某一方法具有相同的方法名、返回类型和参数表,则新方法将覆盖原有的方法。
 
如需父类中原有的方法,可使用super关键字,该关键字引用了当前类的父类。
 
 
    (3)子类函数的访问修饰权限不能少于父类的;



原文地址:https://www.cnblogs.com/shenxiaoquan/p/5706683.html