java重载 覆盖_Java重载和覆盖

小编典典

方法重载意味着根据输入来制作功能的多个版本。例如:

public Double doSomething(Double x) { ... }

public Object doSomething(Object y) { ... }

在编译时选择要调用的方法。例如:

Double obj1 = new Double();

doSomething(obj1); // calls the Double version

Object obj2 = new Object();

doSomething(obj2); // calls the Object version

Object obj3 = new Double();

doSomething(obj3); // calls the Object version because the compilers see the

// type as Object

// This makes more sense when you consider something like

public void myMethod(Object o) {

doSomething(o);

}

myMethod(new Double(5));

// inside the call to myMethod, it sees only that it has an Object

// it can't tell that it's a Double at compile time

方法覆盖意味着通过原始方法的子类定义方法的新版本

class Parent {

public void myMethod() { ... }

}

class Child extends Parent {

@Override

public void myMethod() { ... }

}

Parent p = new Parent();

p.myMethod(); // calls Parent's myMethod

Child c = new Child();

c.myMethod(); // calls Child's myMethod

Parent pc = new Child();

pc.myMethod(); // call's Child's myMethod because the type is checked at runtime

// rather than compile time

希望对您有所帮助

2020-09-09

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值