java中的方法覆盖_有几种方法可以防止Java中的方法覆盖?

java中的方法覆盖_有几种方法可以防止Java中的方法覆盖?

由于Java中的运行时方法绑定功能,方法覆盖起作用。因此,如果我们强制Java编译器对方法进行静态绑定,则可以防止该方法在派生类中被覆盖。

我们可以通过3种方式防止Java中的方法覆盖通过在基类中创建final方法

通过在基类中使方法静态化

通过在基类中将方法设为私有

Final方法不能被重写

通过将一个方法设为final,我们添加了一个限制,即派生类不能覆盖这个特定的方法。

示例class Base {

public void show() {

System.out.println("Base class show() method");

}

public final void test() {

System.out.println("Base class test() method");

}

}

class Derived extends Base {

public void show() {

System.out.println("Derived class show() method");

}

//不能重写test()方法,因为它在基类中是final

/*

* public void test() { System.out.println("Derived class test() method"); }

*/

}

public class Test {

public static void main(String[] args) {

Base ref = new Derived();

//调用final 方法 test()

ref.test();

//调用重写的方法 show ()

ref.show();

}

}

输出结果Base class test() method

Derived class show() method

静态方法不能被覆盖

我们不能覆盖派生类中的静态方法,因为静态方法是与类而不是与对象链接的。这意味着,当我们调用静态方法时,JVM不会像对所有非静态方法一样将此引用传递给它。因此,静态方法无法进行运行时绑定。

示例class Base {

public void show() {

System.out.println("Base class show() method");

}

public static void test() {

System.out.println("Base class test() method");

}

}

class Derived extends Base {

public void show() {

System.out.println("Derived class show() method");

}

//将被视为新方法

public static void test() {

System.out.println("Derived class test() method");

}

}

public class Test {

public static void main(String[] args) {

Base ref = new Derived();

//它将调用 Base 类的 test () ,因为它具有静态绑定

ref.test();

//调用重写的方法 show ()

ref.show();

}

}

输出结果Base class test() method

Derived class show() method

私有方法不能被覆盖

基类的私有方法在派生类中不可见,因此不能覆盖它们。

示例class Base {

public void show() {

System.out.println("Base class show() method");

}

private void test() {

System.out.println("Base class test() method");

}

}

class Derived extends Base {

public void show() {

System.out.println("Derived class show() method");

}

//这不是替代方法,将被视为其他方法。

public void test() {

System.out.println("Derived class test() method");

}

}

public class Test {

public static void main(String[] args) {

Base ref = new Derived();

//无法调用私有方法test(),此行将给出编译时错误

//ref.test();

//调用重写的方法 show ()

ref.show();

}

}

输出结果Derived class show() method

相关拼贴