Java中关于方法重写的规则是什么?
如果超类和子类具有包含参数的同名方法。JVM根据用于调用方法的对象来调用相应的方法。即,如果用于调用该方法的对象是超类类型,则将执行超类的方法。
或者,如果对象属于子类类型,则执行超类的方法。
示例
class Super{
public void sample(){
System.out.println("Method of the Super class");
}
}
public class MethodOverriding extends Super {
public void sample(){
System.out.println("Method of the Sub class");
}
public static void main(String args[]){
MethodOverriding obj = new MethodOverriding();
obj.sample();
}
}输出结果
Method of the Sub class
覆盖方法时应遵循的规则
覆盖时,您需要牢记以下几点-
这两个方法必须具有相同的名称,相同的参数和相同的返回类型,否则它们将被视为不同的方法。
子类中的方法不得具有比超类中的方法更高的访问限制。如果您尝试这样做,则会引发编译时异常。
示例
class Super{
void sample(){
System.out.println("Method of the Super class");
}
}
public class MethodOverriding extends Super {
private void sample(){
System.out.println("Method of the Sub class");
}
public static void main(String args[]){
MethodOverriding obj = new MethodOverriding();
obj.sample();
}
}编译时错误
MethodOverriding.java:7: error: sample() in MethodOverriding cannot override sample() in Super
private void sample(){
^
attempting to assign weaker access privileges; was package
1 error如果超类方法引发某些异常,则子类中的方法应引发相同的异常或其子类型(可以离开而不会引发任何异常)。它不应引发更广泛的例外。如果这样做,则会生成编译时错误。
示例
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
abstract class Super{
public String readFile(String path)throws FileNotFoundException{
throw new FileNotFoundException();
}
}
public class ExceptionsExample extends Super{
@Override
public String readFile(String path)throws IOException {
//方法主体......-
}
}编译时错误
在编译时,上述程序为您提供以下输出-
ExceptionsExample.java:13: error: readFile(String) in ExceptionsExample cannot override readFile(String) in Sup
public String readFile(String path)throws IOException {
^
overridden method does not throw IOException