java 类型强制转换和自动转换

Java的类型从低到高是自动转换 比如 Int – double

int a = 1;
double b = 1.0;
double c = 0.0;
c = a +b;//此处自动转换 int + double = double 类型;

从高到低是强制转换.比如 double – int

int a = 1;
double b = 1.0;
int c = 0;
c = (int)b + a ; //doubel 到int 需要强制转换,

父类高于子类,父类到子类需要强转,

package opp.instanceof父子关系和类型转化;

public class typeConversion类型转换 {
    public static void main(String[] args) {


        //由低到高自动转换如同 int --> double
        //父类高于子类,低到高自动转,高到低强转.
        //高          --        低
        Person person = new Student();
        //person.goToShool();编译错误,需要将Person强制转换为Student
        // 
        Student student = (Student) person;
        student.goToSchool();
        //subclass to parent class 会丢失方法.
        Person person1 = student;//这里会丢失Student特有的方法.

    }
}
发布了56 篇原创文章 · 获赞 2 · 访问量 485

猜你喜欢

转载自blog.csdn.net/jarvan5/article/details/105553613