您的位置:首页 > 其它

SCJP认证 第二章 面向对象 2.4.2重载方法(1)

2011-03-20 15:41 204 查看
重载规则:

重载方法必须改变变元列表。

重载方法可以改变返回类型。

重载方法可以改变访问修饰符。

重载方法可以声明信的更广的检验的异常。

方法能够在同一个类或者一个子类中被重载。

public class Foo {
public void doStuff(int y, String s){ }
public void moreThings(int x){ }
}
class Bar extends Foo{
public void doStuff(int y, long s) throws IOException{ }
}


由于被重写的doStuff()方法没有声明异常,当IOException对编译器而言是个检验异常你可能被误导,认为IOException就是问题。但是doStuff()方法根本没有被重写!子类Bar通过修改变元列表重载了doStuff()方法,因此IOException是不存在问题的。

合法的重载

让我们来看一个要重载方法:

public void changeSize(int size, String name, float pattern){}

// 以下方法是changeSize()方法的合法重载:
public void changeSize(int size, String name){}
public int changeSize(int size, pattern){}
public void changeSize(float pattern, String name) throws IOException{}


调用重载方法

class Adder{
public int addThem(int x, int y){
return x+y;
}

//Overload the addThem method to add doubles instead of ints
public double addThem(double x, double y){
return x + y;
}
}

public class TestAdder{
public static void main(String[] args){
Adder a = new Adder();
int b = 27;
int c = 3;
int result = a.addThem(b, c); // Which addThem is invoked?
double doubleresult = a.addThem(22.5, 9.3);//Which addThem?
}
}


在上面的TestAdder代码中,第一调用a.addThem(b, c) 时向该方法传递两个int,因此,调用addThem()的第一个版本——带两个int变元的版本。第二次调用a.addThem(22.5, 9.3)时,向该方法传递两个double,因此调用addThem()的两个版本——带两个double变元的重载版本。

假如有这样一个重载方法,其一个版本带Animal,另一个版本带Horse(Animal的子类) 。如果在该方法调用中传递一个Horse对象,将调用带Horse的重载版本。先来看一下以下代码:

class Animal {}

class Horse extends Animal{}

class UseAnimal{
public void doStuff(Animal a){
System.out.println("In the Animal version");
}

public void doStuff(Horse h){
System.out.println("In the Horse version");
}

public static void main(String[] args){
UseAnimal ua = new UseAnimal();
Animal animalObj = new Animal();
Horse horseObj = new Horse();
ua.doStuff(animalObj);
ua.doStuff(horseObj);
}
}


输出结果:

in the Animal version

in the Horse version

但是,如果使用对Horse对象的Animal引用,情况如何?

Animal animalRefToHorse = new Horse();
ua.doStuff(animalRefToHorse);


代码会输出:

in the Animal version

即使在运行时实际对象是Horse而不是Animal,但是选择调用哪个重载方法并不是在运行时动态决定的。只需记住,引用类型(不是对象类型) 决定了调用哪个重载方法!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: