public class Test5 {
public static void main(String[] args) {
Person p = new Student("lisi");//此父类对象可以转换成子类对象
Person p2 = new Person("zhaoliu");//此父类对象不可以转换成子类对象
//System.out.println(p.getName());
Student s = new Student("zhangsan","qinghe11zhong");
//System.out.println(s.getName()+":"+s.getSchool());
Person p3 = s;//子类对象可以转换成父类对象
if(p instanceof Student){
Student s1 = (Student) p;
System.out.println("p可以转换成Student的对象");
}
if(p2 instanceof Student){
Student s1 = (Student) p2;
System.out.println("p2可以转换成Student的对象");
}
}
}
class Student extends Person{
private String school;
public Student(String name){
this.setName(name);
}
public Student(String name,String school){
this.setName(name);
this.school = school;
}
public String getSchool(){
return school;
}
}
class Person {
private String name;
public Person(){}
public Person(String name){
this.name=name;
}
public String getName()
{
return name;
}
public void setName(String name){
this.name = name;
}
}
|