java:对象类型转换

在这里插入图片描述
public class Test {

public static void main(String[] args) {

/**

  •   	byte->short->
    
  •                                             int->long->float->double(大)
    
  •                char->
    

*/

	//小的类型自动转换成大的类型
	int i=10;
	long l=i;
	
	
	//大的类型强制转换成小的类型
	long m=101;
	int a=(int) m;
	
	//从子类到父类的类型转换自动进行
	Student stu=new Student();
	Person pa=stu;
	
	String s="zhangsan";
	Object ob=s;//Object 是所有类的最高父类
	
	

	
	//从父类到子类的类型转换必须要强制转换
	Person p=new Person();
	Student st=(Student) p;
	
	Object obj="hello";
	String str=(String) obj;
	
	
}

}
在这里插入图片描述

public class Person {
public void test(){
System.out.println(“这是person的test的方法”);
}

public class Student extends Person {
public void getSchool(){
	System.out.println("这是student的getschool方法");
}

public class Test {

public void method(Person p){
	if(p instanceof Student){//判断p对象是不是属于Student,如果是强制类型转换成student类型
		Student s=(Student) p;
		s.getSchool();
	}else{
		p.test();
	}
}
public static void main(String[] args) {
	
	Test t=new Test();
	
	//t.method( new Person());//第一种
	  t.method( new Student());//第二种
}
结果:这是person的test的方法//第一种
            这是student的getschool方法//第二种
发布了45 篇原创文章 · 获赞 12 · 访问量 1125

猜你喜欢

转载自blog.csdn.net/weixin_46037153/article/details/104440921