gpt4 book ai didi

java - 为什么我会收到方法覆盖错误?

转载 作者:行者123 更新时间:2023-11-29 07:08:01 24 4
gpt4 key购买 nike

这是我的父类(super class):

class Superclass {

int a=89;

final static void m( int p){
System.out.println("Inside superclass");
}

static void n(){
system.out.print("superclass");
}

}

这是我的子类::

 class Subclass extends Superclass {

int a=90;

static void m( int p){
System.out.println("Inside subclass");
}

static void n(){
system.out.print("subclass");
}
}

主类:

   class main {
public static void main(String[] args) {
Subclass.m(89);
new Subclass().n();
}
}

问题是我不明白为什么 Javac 在静态方法中给我重写错误..P.S plzz 详细说明所有重写规则也适用于隐藏。喜欢

The new method definition must have the same method signature (i.e., method name and parameters) and the same return type. Whether parameters in the overriding method should be final is at the discretion of the subclass method's signature does not encompass the final modifier of parameters, only their types and order.

新的

method definition cannot narrow the accessibility of the method, but it can widen it The new method definition can only specify all or none, or a subset of the exception classes (including their subclasses) specified in the throws clause of the overridden method in the superclass

我的错误是:运行:

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - m(int) in javaapplication3.Subclass cannot override m(int) in javaapplication3.Superclass overridden method is static,final at javaapplication3.Subclass.m(JavaApplication3.java:18) at javaapplication3.min.main(JavaApplication3.java:25) Java Result: 1

我还想问一下,当方法被扩展父类(super class)的子类隐藏时,​​是否从类名调用静态成员来解决执行哪个版本的方法如果我创建匿名对象然后调用方法,那么编译器如何确定应该调用哪个版本的方法呢?在上面的主类代码中,我输入:new Subclass().n();

即使我没有提供引用变量的类型,编译器如何知道应该调用方法的子类版本

最佳答案

来自JLS 8.4.3.3 :

A method can be declared final to prevent subclasses from overriding or hiding it.

来自父类的具有相同签名的静态方法是hidden当从子类的实例调用时。但是,您不能覆盖/隐藏 final methods .关键字 final 将禁止方法被隐藏。因此它们不能被隐藏,并且尝试这样做将导致编译器错误。在 Javaranch 上有一个很好的解释.

关于java - 为什么我会收到方法覆盖错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17511675/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com