首先了解多态
- 使用父类类型的引用指向子类的对象;
- 该引用只能调用父类中定义的非private方法和变量;
- 如果子类中重写了父类中的一个方法,那么调用这个方法的时候,将会调用子类中的方法(动态绑定);
- 变量不可以被重写,重写只针对方法,不重写变量;
- 重写就是相同的方法,得到的结果和表现的形式不同;
//父类
public class Father{
//父类有一个打孩子方法
public void hitChild(){
}
}
//子类1
public class Son1 extends Father{
//重写父类打孩子方法
public void hitChild(){
System.out.println("为什么打我?我做错什么了!");
}
}
//子类2
public class Son2 extends Father{
//重写父类打孩子方法
public void hitChild(){
System.out.println("我知道错了,别打了!");
}
}
//子类3
public class Son3 extends Father{
//重写父类打孩子方法
public void hitChild(){
System.out.println("我跑,你打不着!");
}
}
//测试类
public class Test{
public static void main(String args[]){
Father father;
father = new Son1();
father.hitChild();
father = new Son2();
father.hitChild();
father = new Son3();
father.hitChild();
}
}
向上转型的意义:程序开始的时候确定有一个father型对象,但是要根据用户的选择来决定他要被实例化成哪种类型的。但如果你要分开来声明的话,那你就因为不确定性必须要声明两个变量,分别来等待实例化。就是实例化的时候可以根据不同的需求实例化不同的对象,这也就是多态的意义。