多态是java中面向对象的四个基本特性之一,是面向对象程序设计中代码重用的一个重要机制,它表示了同一个操作作用在不同对象时,会有不同的语义,进而产生不同的结果。
package test;
public class Father {
public void print() {
System.out.println("我是father");
}
public static void main(String[] args) {
Father p1 = new Father();
Father p2 = new son();//向上转型
son s = new son();
p1.print();
p2.print();
s.print();
s.play();
}
}
class son extends Father{
@Override
public void print() {
System.out.println("我是son");
}
public void play() {
System.out.println("我是son,我能够玩耍");
}
}
运行截图:
此外向上转型还可以实现参数统一化:
//参数统一化
class Person{
public void print() {
System.out.println("1.Person类的print方法");
}
}
class Student extends Person{
public void print(){
System.out.println("2.Student类的print方法");
}
}
class Worker extends Person{
public void print(){
System.out.println("3.Worker类的Print方法");
}
}
public class Text6{
public static void main(String[] args){
fun(new Person());//Person per = new Person();
fun(new Student());//Person per = new Student();//向上转型 Student类 转为 Person类
fun(new Worker());//Person per = new Worker();//向上转型 Worker 类 转为 Person类
}
public static void fun(Person per){
per.print();
}
}
//运行结果:
//1.Person类的print方法
//2.Student类的print方法
//3.Worker类的Print方法
//向下转型 将父类对象转为子类
class Person{
public void print(){
System.out.println("1.我是爸爸!");
}
}
class Student extends Person{
public void print(){
System.out.println("2.我是儿砸!");
}
public void fun(){
System.out.println("3.只有儿砸有!");
}
}
public class Text8{
public static void main(String[] args){
Person per = new Student();//向上转型
per.print();//能够调用的只有父类已定义好的
Student stu = (Student) per;//向下转型
stu.fun();//
}
}
父类需要子类扩充的属性或方法时需要向下转型;并不是所有父类都可以向下转型,如果想要向下转型之前,一定要首先发生向上转型过程,否则会出现ClassCastException(类型转换异常 属于运行时异常)。两个没有关系的类是不能发生转型的,一定会产生ClassCastException.
解释:就是一个父类对象能够转成子类对象一定得是new一个子类实例得到的,这样才能转成子类对象,如果是一个new一个父类实例转成子类就会报错。看下面这个例子:
package test;
public class Father {
public void print() {
System.out.println("我是father");
}
public static void main(String[] args) {
Father p1 = new Father();
Father p2 = new son();
try {
son s = (son)p1;
s.play();
System.out.println();
}catch(ClassCastException e) {
System.err.println("p1转成子类失败");
}
son s2 = (son)p2;
s2.play();
}
}
class son extends Father{
@Override
public void print() {
System.out.println("我是son");
}
public void play() {
System.out.println("我是son,我能够玩耍");
}
}
运行结果:
package test;
public class Father {
public void print() {
System.out.println("我是father");
}
public static void main(String[] args) {
Father p1 = new Father();
Father p2 = new son();
System.out.println("p1是否指向Father:"+(p1 instanceof Father));
System.out.println("p1是否指向sonFather:"+(p1 instanceof son));
System.out.println("p2是否指向Father:"+(p2 instanceof Father));
System.out.println("p2是否指向son:"+(p2 instanceof son));
}
}
class son extends Father{
@Override
public void print() {
System.out.println("我是son");
}
public void play() {
System.out.println("我是son,我能够玩耍");
}
}
运行截图:
因篇幅问题不能全部显示,请点此查看更多更全内容