類型轉換(向下強制)
1. 向上轉型比較安全
int i =1;
double result = i ;
Employee e = new Manager();
2. 向下轉型不安全(因爲父類中不一定有子類的一些屬性和方法),需要強制轉換
double d=4.9999999;
int result = (int) d ;
Manager m = (Manager)new Employee();//(另需要是由子類做底層構建)
double
float
int
Employee
Manager
Boss
另: int a = 5;
float b= (float) 5.0;
long c = 5L;
//5.0是double型,其它兩項必須轉型纔有匹配的方法test(double a ,double b,double c)可以用
test(5,5.0,5L) //-->1
// 如果有顯示定義類型就按照類型判斷
test (a,b,c) //-->2
void test(double a ,double b,double c){
System.out.println("1---"+a+"=="+b+"=="+c); //1---5.0==5.0==5.0
}
void test(int a ,float b,long c){
System.out.println("2---"+a+"=="+b+"=="+c); //2--5==5.0==5
}
5.0 自動轉換到double
3.對象引用的類型決定了哪個變量可以訪問,底層對象的類型決定了哪個方法可以調用(屬性=方法)
class Acc{
public static void main(String[] args){
First s = new Second(); //First s = new First(); ClassCaseException
Second s2 = (Second)s;
System.out.println("s.var="+s.var); // s.var=1
System.out.println("s.method()="+s.method()); //s.method()=2
System.out.println("s2.var="+s2.var); // s2.var=1
System.out.println("s2.method()="+s2.method()); //s2.method()=2
}
}
class First{
int var =1;
int method(){
return var;
}
}
class Second extends First{
int var = 2;
int method(){
return var;
}
}