overloading & overriding

重载(Overloading)
  • 方法重载是让类以统一的方式处理不同类型数据的一种手段。多个同名函数同时存在,具有不同的参数个数/类型。重载Overloading是一个类中多态性的一种表现。
  • Java的方法重载,就是在类中可以创建多个方法,它们具有相同的名字,但具有不同的参数和不同的定义。调用方法时通过传递给它们的不同参数个数和参数类型来决定具体使用哪个方法, 这就是多态性。
  • 重载的时候,方法名要一样,但是参数类型和个数不一样,返回值类型可以相同也可以不相同。无法以返回型别作为重载函数的区分标准。(method signature is the unique identifier of a method and signature does not contain return type)
重写(Overriding)
  • 父类与子类之间的多态性,对父类的函数进行重新定义。如果在子类中定义某 方法与其父类有相同的名称和参数,我们说该方法被重写 (Overriding)。在Java中, 子类可继承父类中的方法,而不需要重新编写相同的方法。但有时子类并不想原封不 动地继承父类的方法,而是想作一定的修改,这就需要采用方法的重写。方法重写又 称方法覆盖。
  • 若子类中的方法与父类中的某一方法具有相同的方法名、返回类型和参数表, 则新方法将覆盖原有的方法。如需父类中原有的方法,可使用super关键字,该关键 字引用了当前类的父类
  • 子类函数的访问修饰权限不能少于父类的

转自stackoverflow Overloading is having multiple methods in a single class where the method has the same name. However, the return value is not seen as part of the signature of the method. Thus, you cannot overload a method by changing only the return value. You cannot have the following code, from your example:

public void setValue() {   
    this.value= 0;
}

public int setValue() {   
    returnthis.value;
} 

This will fail to compile.

As Rob identified, I believe you mean overriding, and you have that correct. Note with overriding, you cannot change the return type. As of Java 5, you can return a derived type of what the base class method returned. Before Java 5, it must be the identical type. That is, you cannot do the below until Java 5 and later:

public class AnimalNoise{}
public class MiawextendsAnimalNoise{}

public class Animal{
    public AnimalNoise makeNoise(){
        return newAnimalNoise();
    }
}

public class Cat extends Animal{
    public Miaw makeNoise(){
        return newMiaw();
    }
}

However, even in Java 5 and later, you cannot do the following:

public class Animal{
    public String makeNoise(){
        return "silence";
    }
}

public class Cat extends Animal{
    public Miaw makeNoise(){
        return new Miaw();
    }
}
public class Miaw{}


Finally, a big difference between overloading and overriding that is often overlooked is that overloading is decided at compile time and overriding is decided at runtime. This catches many people by surprise when they expect overloading to be decided at runtime.

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值