Java中不同包的重写方法
已测试
重写的优势在于能够定义特定于子类类型的行为,这意味着子类可以根据其需求实现父类方法。
在面向对象术语中,重写意味着重写现有方法的功能。
示例
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方法。原因是:在编译时,检查是在引用类型上进行的。但是,在运行时,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:26: error: cannot find symbol b.bark(); ^ symbol: method bark() location: variable b of type Animal 1 error
此程序将抛出编译时错误,因为b的引用类型Animal没有名为bark的方法。
方法重写的规则
参数列表必须与被重写方法的参数列表完全相同。
返回类型应与超类中原始被重写方法中声明的返回类型相同或为其子类型。
访问级别不能比被重写方法的访问级别更严格。例如:如果超类方法声明为public,那么子类中的重写方法不能是private或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
测试
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP