本文主要是介绍instanceof关键字和向上向下转型,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
instanceof关键字和向上向下转型
public class Computer {//电脑
public static void main(String[] args) {
Pad pad = new Pad();
HuaWeiPad huaWeiPad = new HuaWeiPad();
System.out.println("pad是否继承自电脑?"+(pad instanceof Computer));
System.out.println("pad是否继承自电脑?"+(huaWeiPad instanceof Pad));
System.out.println("pad是否继承自电脑?"+(huaWeiPad instanceof Computer));
System.out.println("pad是否继承自电脑?"+(pad instanceof HuaWeiPad));
}
}
class Pad extends Computer{//平板电脑
}
class HuaWeiPad extends Pad{//华为平板电脑
}
public class Person {
public Person(String name){
System.out.println("你好,我叫"+name);
}
}
public class Student extends Person {
public Student(String name) {
super(name);
}
}
public class Doctor extends Person{
public Doctor(String name) {
super(name);
}
}
public class Test {
public static void main(String[] args) {
Person tom = new Student("tom");//向上转型,由父类声明了一个对象,由子类来实例化
Student st = (Student) tom;
Person jack = new Doctor("jack");//向下转型,强制转型,父类对象要先引用这个子类对象
Doctor dr = (Doctor) jack;
}
}
这篇关于instanceof关键字和向上向下转型的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!