欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java类型转换

程序员文章站 2022-03-24 17:23:14
...

Java支持的类型转换:

1.类型转换原生数据类型

隐式转换:

数据类型自动转换为另一种数据类型,发生前提是两种数据类型彼此兼容

较小数据类型放入较大数据类型

int a=100;
long b=a;

显式转换:

必须是转换为兼容类型

较大数据类型放入较小数据类型

longa=100;
int b=(int)a;

2.对象的类型转换

向上转型

向下转型

Java类型转换

向上转型:子类引用赋值给父类引用

Employee e1=new Employee();
Manager mgr=new Manager();
e1=mgr;

向下转型:子类实例化父类

public class Employee {

	private int id;
	private String name;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String toString() {
		return "Employee [id=" + id + ", name=" + name + "]";
	}
	
}
public class Manager extends Employee {

	
	private int bonus;

	public int getBonus() {
		return bonus;
	}

	public void setBonus(int bonus) {
		this.bonus = bonus;
	}

	public String toString() {
		return "Manager [bonus=" + bonus + ", toString()=" + super.toString()
				+ "]";
	}
	

}
public class Test {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Employee e1=new Manager();//向下转型
		e1.setId(12);
		e1.setName("xiaoming");
		//虽然使用Manager实例化的e1,但是e1却没有Manager的bonus属性,必须强转为Manager
		Manager magr=(Manager) e1;
		magr.setBonus(10000);
		System.out.println(e1);
		System.out.println(magr);
		//e1和magr的内容相同,因为是同一个引用
		/*
		 * Manager [bonus=10000, toString()=Employee [id=12, name=xiaoming]]
		 * Manager [bonus=10000, toString()=Employee [id=12, name=xiaoming]]
		 */
		Employee e2=magr;//向上 转型
		e2.setId(2);//e1没有Manager的bonus属性
		System.out.println(e2);
		System.out.println(e1);
		System.out.println(magr);
		/*
		 * Manager [bonus=10000, toString()=Employee [id=2, name=xiaoming]]
		 * Manager [bonus=10000, toString()=Employee [id=2, name=xiaoming]]
         * Manager [bonus=10000, toString()=Employee [id=2, name=xiaoming]]
		 */
		//同一个引用
	}

}

在其位谋其职,要想弄明白是否能调用setBonus()就要看他的声明类型,而不是看他转换为了什么类型,这个要明白

        Employee e=new Employee();
		e.setId(23);
		e.setName("lili");
		Manager m1=new Manager();
		m1=(Manager)e;//Code.Employee cannot be cast to Code.Manager
						//报错了,弄明白再转
Employee e=new Employee();
		e.setId(23);
		e.setName("lili");
		Manager m1=new Manager();
		//m1=(Manager)e;//Code.Employee cannot be cast to Code.Manager
						//报错了,弄明白再转
		m1.setId(12);
		m1.setName("wangwu");
		m1.setBonus(12233);
		System.out.println(m1);
		System.out.println(e);
		/*
		 * Manager [bonus=12233, toString()=Employee [id=12, name=wangwu]]
		 * Employee [id=23, name=lili]
		 */