什么是多态(向上转型)

多态:

通俗的说,多态是由于继承结构的存在一个类有多个导出类,表现的出多种行为;
具体的讲,多态就是将导出类看做是它的基类,通过动态绑定,实现多种不同的行为。

  1. 向上转型

将导出类看做是它的基类的过程称为向上转型(upcasting)

void doSomethings(Shape shape) {
	shape.erase();
	shape.draw();
}

Circle circle = new Circle();
Triangle triangle = new Triangle();
Line line = new Line();
doSomethings(circle);
doSomethings(triangle);
doSomethings(line);

1.只有非private方法才能被覆盖,private方法不具有多态性;
2.静态方法不具有多态性。
3.编写构造器时有一条有效的准则:“用尽可能简单的方法使对象进入正常状态,如果可以的话,避免调用其他方法”,在构造器内部唯一能够安全的调用的那些方法是基类中的final方法(也适用于private方法,它们自动属于final)。

  1. 向下转型
    向下转型是不安全的。
class Useful {
    public void f() {
    }

    public void g() {
    }
}

class MoreUseful extends Useful {
    @Override
    public void f() {
    }

    public void g() {
    }

    public void u() {
    }

    public void v() {
    }

    public void w() {
    }
}

/**
 * @Author ZhangGJ
 * @Date 2020/11/16 08:28
 */
public class RTTI {
    public static void main(String[] args) {
        Useful[] x = {new Useful(), new MoreUseful()};
        x[0].f();
        x[1].g();
        // Compile time: method not found in Useful:
//        x[1].u();
        /**
         * Downcast/RTTI
         */
        ((MoreUseful) x[1]).u();
        /**
         * Exception thrown
         */
        ((MoreUseful) x[0]).u();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值