gpt4 book ai didi

java - 子类可以覆盖方法并具有不同的参数吗?

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

我想在多个子类中有一个方法,它基本上可以完成某件事(比如获取用户信息),但在主类中声明(并且具有与主类不同的参数和定义)。这可能吗?

我知道这并不是真正的压倒一切,但可以这样做吗,或者它不是一种合适的构造方法的方式吗?

最佳答案

你要做的就是重载一个方法。这是可行的,而且经常发生。 Play with the fiddle here. Java 类似。

public class Parent
{
public virtual string HelloWorld()
{
return "Hello world";
}

public string GoodbyeWorld()
{
return "Goodbye world";
}
}

public class Child : Parent
{
// override: exact same signature, parent method must be virtual
public override string HelloWorld()
{
return "Hello World from Child";
}

// overload: same name, different order of parameter types
public string GoodbyeWorld(string name)
{
return GoodbyeWorld() + " from " + name;
}
}

public class Program
{
public static void Main()
{
var parent = new Parent();
var child = new Child();
Console.WriteLine(parent.HelloWorld());
Console.WriteLine(child.HelloWorld());
Console.WriteLine(child.GoodbyeWorld());
Console.WriteLine(child.GoodbyeWorld("Shaun"));
}
}

关于java - 子类可以覆盖方法并具有不同的参数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28887875/

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