instanceof和类型转换
判断一个对象是什么类型:instanceof
x instanceof y
package com.oop;
import com.oop.demo06.Person;
import com.oop.demo06.Student;
import com.oop.demo06.Teacher;
public class Application {
public static void main(String[] args) {
Object object = new Student();
System.out.println(object instanceof Student);
System.out.println(object instanceof Person);
System.out.println(object instanceof Object);
System.out.println(object instanceof Teacher);
}
}
类型转换
-
父类引用指向子类对象
-
把子类对象转换为父类,向上转型,自动转换
-
把父类对象转换为子类,向下转型,强制转换
-
方便方法调用,减少重复代码
package com.oop.demo06; public class Person { public void run(){ System.out.println("run"); } }
public class Student extends Person{ public void go(){ System.out.println("go"); } }
package com.oop; import com.oop.demo06.Person; import com.oop.demo06.Student; import com.oop.demo06.Teacher; public class Application { public static void main(String[] args) { //类型之间的转换 //高 低 Person obj = new Student(); //将student转换为Student类型,就可以使用Student类型的方法了 ((Student)obj).go(); //Student student = (Student)obj; //student.go(); //子类转父类,可能会丢失自己本来的一些方法 Student s1 =new Student(); Person s2=s1; } }
标签:instanceof,类型转换,Day8,Person,oop,Student,com,public From: https://www.cnblogs.com/actadams68/p/16903054.html