class TestOverriding {
public static void main(String aga[]) {
Test t = new Fest();
t.tests();
}
}
class Test {
void tests() {
System.out.println("Test class : tests");
}
}
class Fest extends Test {
static void tests() {
System.out.println("Fest class : tests");
}
}
Run Code Online (Sandbox Code Playgroud)
测试类是超类,而Fest是它的子类,因为即使我们知道静态方法也不能被覆盖,否则我会收到类似“静态方法无法在Java中隐藏实例方法”的错误,有人可以对此进行解释,在此先感谢。
术语覆盖通常用于对象,因为使用相同的父引用,您可以从给定的子对象调用不同的方法。通过这种方式,静态方法不能被重写,因为它们与引用类型相关联,而不是与对象类型相关联。
压倒一切是如何发生的?您在基类中指定一个方法并在子类中放置相同的签名,这会自动覆盖该方法。如果您注意到,静态方法也是继承的,即如果父类包含静态方法,那么它可以被子类引用使用。例如:
public class TestOverriding {
public static void main(String aga[]) {
Fest t = new Fest();
t.tests(); <-- prints "Test class : tests"
}
}
class Test {
static void tests() {
System.out.println("Test class : tests");
}
}
class Fest extends Test {
void tests3() {
System.out.println("Fest class : tests");
}
}
Run Code Online (Sandbox Code Playgroud)
现在,您的子类中已经有了一个静态方法,并且您正在尝试在子类中定义具有相同签名的新方法。这是造成问题的原因。如果您在单个类中执行此操作,错误消息会有所不同。
案例一:同班
class Fest{
void tests3() {
System.out.println("Fest class : tests3");
}
static void tests3() {
System.out.println("Fest class : static tests3"); <-- gives "method tests3() is already defined in class Fest"
}
}
Run Code Online (Sandbox Code Playgroud)
情况2:子类(静态到实例)
class Test {
static void tests() {
System.out.println("Test class : tests");
}
}
class Fest extends Test {
void tests() { <-- gives "overridden method is static"
System.out.println("Fest class : tests");
}
}
Run Code Online (Sandbox Code Playgroud)
情况2:子类(实例转静态)
class Test {
oid tests() {
System.out.println("Test class : tests");
}
}
class Fest extends Test {
static void tests() { <-- gives "overriding method is static"
System.out.println("Fest class : tests");
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4718 次 |
| 最近记录: |