多态-练习题
1、判断正误
double d = 13.4;
longl = (long)d;
System.out.println(l);
int in = 5;
boolean b =(boolean)in;
Object obj="Hello";
String objStr = (String)obj;
System.out.println(objstr);
Object objPri = new Integer(5);
String str = (String)objPri;
lnteger str1 = (lnteger)objPri;
double d = 13.4; //ok
longl = (long)d; //ok
System.out.println(l); //13
int in = 5;//ok
boolean b =(boolean)in; //不对,boolean类型不参与强制类型转换
Object obj=“Hello”;//可以,向上转型
String objStr = (String)obj;//可以,向下转型
System.out.println(objstr); //hello
Object objPri = new Integer(5);//可以,向上转型
String str = (String)objPri;//错误ClassCastException,指向Integer的父类引用,转成String
lnteger str1 = (lnteger)objPri;//可以,向下转型
2、分析输出
class Base {
int count = 10;
public void display(){
System.out.println(this.count);
}
}
class Sub extends Base {
int count = 20;
public void display(){
System.out.println(this.count);
}
}
public class Test02 {
public static void main(String[] args) {
Sub s = new Sub();
System.out.println(s.count);
s.display();
Base b = s;
System.out.println(b == s);
System.out.println(b.count);
b.display();
}
}
我的分析out:
20
20
false? × 这里是true
10
20
属性看编译类型,方法看运行类型