instanceof 判断两者是否有继承关系
调用类
package Demo04;
public class Application {
public static void main(String[] args) {
//instanceof 一条线的线性指向关系,在这条线的为true
//主要与左边的类型有关,右边为指向关系
//Object>Person>Student || Teacher
Student student = new Student();
System.out.println(student instanceof Student);//true
System.out.println(student instanceof Person);//true
System.out.println(student instanceof Object);//true
//System.out.println(student instanceof Teacher);//编译错误
//Studnet 与 Teacher 为同类
System.out.println("=======================");
Person person = new Student();
System.out.println(person instanceof Student);//true
System.out.println(person instanceof Person);//true
System.out.println(person instanceof Object);//true
System.out.println(person instanceof Teacher);//false
//Person类引用指向为Student与Teacher无关
System.out.println("=======================");
Object object = new Student();
System.out.println(object instanceof String);//false
//Object>String || Person object应该是与Person有线性的关系
System.out.println(object instanceof Person);//true
}
}
父类
package Demo04;
public class Person {
}
子类
package Demo04;
public class Student extends Person {
}
package Demo04;
public class Teacher extends Person{
}
子类父类间的转换
子类转向父类自动转化 低转高自动
调用类
package Demo04;
public class Application {
public static void main(String[] args) {
//可以理解为student子类类自动转为父类Person类
Person student = new Student();
}
}
父类
package Demo04;
public class Person {
}
子类
package Demo04;
public class Student extends Person {
}
父类转化为子类需要强制转换 ,高转低强制
调用类
package Demo04;
public class Application {
public static void main(String[] args) {
Person person = new Student();
//person.go();//报错子类的独有方法父类不能直接调用
//通过强制转换的方式调用子类的方法
((Student) person).go();//go
Student student = new Student();
student.say();//say
student.go();//go
//子类不仅可以调用自己的方法还继承了父类的方法
}
}
父类
package Demo04;
public class Person {
public void say(){
System.out.println("say");
}
}
子类
package Demo04;
public class Student extends Person {
//子类中定义了一个方法父类不能直接调用
public void go(){
System.out.println("go");
}
}