第一个 一定错 sub继承base
第2个 默认为0
第2个 默认为0
解决方案 »
- 在线等!!!swing Jtable 单元格编辑后,数据自动保存并更新到数据库中???
- java中如何用System.arraycopy去COPY一个自定义类的数组?
- 如何 让JTable的选择模式只能选择单元格
- 读txt文件的问题
- transient | strictfp | volatile是什么意思???
- 请问编程时,什么时候该用到静态方法(看起来好像调用挺方便,好像速度也快),什么时候用 非静态方法 (((很迷茫)))
- 在JBuilder 中如何倒入类库(.jar包)呢?请知道的人帮帮忙!!
- 怎么取得文件长度?
- 谁看过《精通Servlets——Java平台的服务器端编程》这本书,给个评价,是否适合初学者?另外这本书的出版日期是2002年3月1日是不是老了点
- 请问哪儿有JavaTM 2 Platform, Standard Edition v 1.3.1 下载??高分相赠!
- 那位大虾知道下载CodeWarrior for Java的地方?
- ----为什么没有"helloworld"?
如果
Sub a=new Base();
Base b=(Sub)a;
是可以的
想想:
class 动物:
class 人 extends 动物;
如果
动物 a=new 动物();
人 b=(人)a;
那么b就缺少人的部分,不能正常操作
但是
人 a=new 人();
动物 b=(动物)a;
b就指向a中的动物部分,可以正常操作第二个:类里的变量都有初值,但方法里的变量就没有初值。
1、Without the cast to sub you would get a compile time error.
参考译文:如果没有(显式)到 sub 的 cast 的话,你将会得到一个编译错误。
注意 would 的用法,虚拟语态。这句话的意思其实是,例子中因为有 cast 到 sub,所以不会有编译错误!2、Class level variables are always initialised to default values. In the case of an int this will be 0. Method level variables are not given default values and if you attempt to use one before it has been initialised it will cause the Error Variable i may not have been initialized
参考译文:类级别的变量总是被初始化成缺省值。在这种情况(即例子情况)下 int 会是 0。在类的方法一级的变量是不会被赋初值的,如果你在变量被初始化前使用它,将会得到一个错误:变量 i 可能未被初始化。看样子你还是应该同时也补习一下英文呀,否则小心理解得正好相反可就糟了。 :)-----------------------------------------------
public class t
{
static int i;
public static void main(String argv[])
{
System.out.println(i);
}
}
Class level variables are always initialised to default values. In the case of an int this will be 0. Method level variables are not given default values and if you attempt to use one before it has been initialised it will cause the Error Variable i may not have been initialized
是这样的,SCJP的标准答案是:
1 选择a. error variable i may not have been initialized
2 选择c. runtime exception
这难道不是说是出错的吗
1、what will happen if you attempt to compile and run the following code:
class Base {}
class Sub extends Base {}
class Sub2 extends Base {}public class t
{public static void main(String argv[])
{
Base b = new Base();
Sub s = (Sub)b;
}
}
a.Compile and run without error
b.Compile time Exception
c.Runtime Exception (answer:right)2、what will happen when you compile the following code:
public class t
{
static int i;
public static void main(String argv[])
{
System.out.println(i);
}
}
a.error variable i may not have been initialized (answer:right)
b.null
c.1
d.0
会导致一个 ClassCastException(是RunTimeException的子类)2我作了试验了,是d书上(咬咬牙)
是不是书上错了。。嘻嘻
第一题答案是
c.Runtime Exception (answer:right)
因为,子类才能赋值给父类(这当然是对的)这条规则是在runtime时候才体现出来的,编译时只要casting转换正确就行。第二题答案是
d.0
因为,如大家所说,i是class variable, 故不仅有缺省值,而且可以直接引用。一般是用t.i引用,但这里是在自己的main函数里,所以可以把t.i简写为i。清楚了吗?
我刚考完scjp。
模拟题上有些答案也会错的。