gpt4 book ai didi

java - 未定义 Base 类型的子方法

转载 作者:行者123 更新时间:2023-12-02 12:23:42 25 4
gpt4 key购买 nike

public class Base {
public String Method1() {
System.out.println("Inside Base method 1");
return "";
}
}
class Child extends Base {
static Base o = null;
public String Method1() {
System.out.println("Inside Base method 1");
return "";
}
public String Method2() {
return "Cant be called with base reference";
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Base base = new Child();
base.Method1();
base.Method2();***(Error : **The method Method2() is undefined for the type Base**)***
}
}

正如代码所示,我想知道,内存分配中实际发生了什么,隐藏了 Base 调用 Child 的额外方法以及它的名称有没有一种方法可以通过 Base 调用方法。请帮忙

最佳答案

base.Method2() 无效,因为基类没有具有该名称的方法,这就是错误的含义

The method Method2() is undefined for the type Base

既然你这样做了:

Base base = new Child();

你有一个选择是强制转换,然后你可以调用该方法...

Base base = new Child();
base.Method1();
((Child) base).Method2();

关于java - 未定义 Base 类型的子方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45582209/

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