我们能否在 Java 中将主 () 方法声明为 final?
是的,我们在 Java 中可以将 main () 方法声明为final。编译器不会引发任何错误。
- 如果我们通过放置 final 关键字将任何方法声明为 final,那么该方法将成为final 方法。
- final 方法在 Java 中的主要用途是它们不会被覆盖。
- 我们在子类中无法覆盖final 方法。
- 如果我们使用继承并且我们需要一些方法在子类中不被覆盖,那么我们需要使其成为 final,这样那些方法就不能被子类覆盖。
- 我们可以在子类中访问final 方法,但我们无法覆盖 final 方法。
示例
class BaseClass {
public final void show(Object o) {
System.out.println("BaseClass method");
}
}
class DerivedClass extends BaseClass {
public void show(Integer i) {
System.out.println("DerivedClass method");
}
}
public class Test {
public static final void main(String[] args) { // declaring main () method with final keyword.
BaseClass b = new BaseClass();
DerivedClass d = new DerivedClass();
b.show(new Integer(0));
d.show(new Integer(0));
}
}输出
BaseClass method DerivedClass method
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP