我一直在玩静态方法的修饰符,并遇到了一个奇怪的行为.
我们知道,静态方法不能被覆盖,因为它们与类而不是实例相关联.
所以,如果我有下面的代码片段,它编译得很好
//Snippet 1 - Compiles fine
public class A {
static void ts() {
}
}
class B extends A {
static void ts() {
}
}
Run Code Online (Sandbox Code Playgroud)
但是如果我在A类中将final修饰符包含到静态方法中,则编译失败 ,B中的ts()不能覆盖A中的ts(); 重写方法是静态最终的.
当静态方法根本无法被覆盖时,为什么会发生这种情况?
在main方法参数中添加final关键字可以正常工作.为什么它没有给出任何编译器错误/异常,因为我修改了java的标准main方法.
public class StackOverFlow {
public static void main(final String... args) {
System.out.println("Hi");
}
}
Run Code Online (Sandbox Code Playgroud)
现在看看我是否编码:
public class StackOverFlow {
public static void main (String... args) {
String[] str = {"I ", "haven't ", "received ", "my ", "answer." };
args[0] = "hi";
System.out.println(args[0]);
args =str;
for(int i=0; i<args.length; i++) {
System.out.print(args[i]);
}
}
}
Run Code Online (Sandbox Code Playgroud)
对于上面的编码,当您通过传递参数来运行程序时
javac StackOverFlow Nisrin
我的程序输出是
嗨
我没有收到我的答复.
与final关键字同样如此
public class StackOverFlow {
public static void main (final String... args) {
String[] str = {"I ", …Run Code Online (Sandbox Code Playgroud)