Java 重载
<上一节
下一节>
上一节我们讨论了类的继承,如果一个子类从父类继承了一个方法,只要该方法不被标记为final,那么子类就能够重载该方法。
重载的好处在于子类可以根据需要,定义特定于自己的行为。
也就是说子类能够根据需要实现父类的方法。
在面向对象原则里,重载意味着可以重写任何现有方法。
例子:
这是由于在编译阶段,只是检查参数的引用类型。
然而在运行时,Java虚拟机(JVM)指定对象的类型并且运行该对象的方法。
因此在上面的例子中,之所以能编译成功,是因为Animal类中存在move方法,然而运行时,运行的是特定对象的方法。
思考以下例子:
重载的好处在于子类可以根据需要,定义特定于自己的行为。
也就是说子类能够根据需要实现父类的方法。
在面向对象原则里,重载意味着可以重写任何现有方法。
例子:
class Animal{
public void move(){
System.out.println("Animals can move");
}
}
class Dog extends Animal{
public void move(){
System.out.println("Dogs can walk and run");
}
}
public class TestDog{
public static void main(String args[]){
Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object
a.move();// runs the method in Animal class
b.move();//Runs the method in Dog class
}
}
运行结果如下:
Animals can move Dogs can walk and run在上面的例子中可以看到,尽管b属于Animal类型,但是它运行的是Dog类的move方法。
这是由于在编译阶段,只是检查参数的引用类型。
然而在运行时,Java虚拟机(JVM)指定对象的类型并且运行该对象的方法。
因此在上面的例子中,之所以能编译成功,是因为Animal类中存在move方法,然而运行时,运行的是特定对象的方法。
思考以下例子:
class Animal{
public void move(){
System.out.println("Animals can move");
}
}
class Dog extends Animal{
public void move(){
System.out.println("Dogs can walk and run");
}
public void bark(){
System.out.println("Dogs can bark");
}
}
public class TestDog{
public static void main(String args[]){
Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object
a.move();// runs the method in Animal class
b.move();//Runs the method in Dog class
b.bark();
}
}
运行结果如下:
TestDog.java:30: cannot find symbol
symbol : method bark()
location: class Animal
b.bark();
^
该程序将抛出一个编译错误,因为b的引用类型Animal没有bark方法。
方法重载的规则:
- 参数列表应该和被重载的方法完全一致。
- 返回值类型应该和父类中被重载的方法的返回值相同或者相互兼容。
- 访问权限不能比父类中被重载的方法的访问权限更高。例如:如果父类的一个方法被声明为public,那么在子类中重载该方法就不能声明为protected。
- 父类的成员方法只能被它的子类重载。
- 声明为final的方法不能被重载。
- 声明为static的方法不能被重载,但是能够被再次声明。
- 如果一个方法不能被继承,那么该方法不能被重载。
- 子类和父类在同一个包中,那么子类可以重载父类所有方法,除了声明为private和final的方法。
- 子类和父类不在同一个包中,那么子类只能够重载父类的声明为public和protected的非final方法。
- 重载的方法能够抛出任何非强制异常,无论被重载的方法是否抛出异常。但是,重载的方法不能抛出新的强制性异常,或者比被重载方法声明的更广泛的强制性异常,反之则可以。
- 构造方法不能被重载。
Super关键字的使用:
当需要在子类中调用父类的被重载方法时,要使用super关键字。
class Animal{
public void move(){
System.out.println("Animals can move");
}
}
class Dog extends Animal{
public void move(){
super.move(); // invokes the super class method
System.out.println("Dogs can walk and run");
}
}
public class TestDog{
public static void main(String args[]){
Animal b = new Dog(); // Animal reference but Dog object
b.move(); //Runs the method in Dog class
}
}
运行结果如下:
Animals can move Dogs can walk and run
<上一节
下一节>
