person类
class person{
private int age;
private String name;
public person(){
}
public person(int age,String name){
this.age=age;
this.name=name;
}
public void sleep(){
System.out.println("person is sleeping");
}
}
student类
class student extends person{
private String id;
public student(){
}
public student(int age, String name){
super(age,name);
}
public student(int age,String name,String id){
super(age,name);
this.id=id;
}
public void sleep(){
System.out.println("student is sleeping");
}
public void sleep(int i){
System.out.println(i+" student is sleeping");
}
}
main方法
public class OverloadingAndOverriding {
public static void main(String[] args) {
// TODO Auto-generated method stub
person p1=new person(12, "zz");
p1.sleep();
student s1=new student(12, "z");
s1.sleep();
s1.sleep(1);
person p2=new student();//父类到子类 向上转型
p2.sleep();
if (p2 instanceof student) {//子类到父类 向下转型 先进行类型检查
student s2 = (student) p2;//子类到父类 安全的强制向下转型
s2.sleep();
}
}
}
运行结果:
person is sleeping
student is sleeping
1 student is sleeping
student is sleeping
student is sleeping