java 子类可以覆盖方法并具有不同的参数吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28887875/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can a subclass override a method and have different parameters?
提问by user3587754
I want to have a method in multiple subclasses which essentially get a certain thing done (like getting user info), but is declared in (and has different parameters and definitions than) the main class. Is this possible?
我想在多个子类中有一个方法,它基本上可以完成某件事(例如获取用户信息),但在主类中声明(并且具有与主类不同的参数和定义)。这可能吗?
I know this is not really overriding, but can this be done or is it not a suitable way to structure methods?
我知道这并不是真正的压倒一切,但这是否可以完成,或者它不是构建方法的合适方式?
回答by Shaun Luttin
What you want to do is called overloading a method. It is doable and occurs often. Play with the fiddle here.Java is similar.
您想要做的称为重载方法。这是可行的并且经常发生。在这里玩小提琴。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"));
}
}
回答by muasif80
You can have multiple versions of a method with the same name having different number of parameters. You can have all these in the main/parent class or you can add the newer versions in the subclasses only. There is no restriction on doing this.
您可以有多个版本的同名方法具有不同数量的参数。您可以在主/父类中拥有所有这些,也可以仅在子类中添加较新的版本。这样做没有限制。
回答by KSFT
As stated in the comments and the other answer, you can define a method in a subclass with the same name as a method in its superclass, but you can't override it, exactly. Both methods will still exist, so it's called overloading. In Javaand in C Sharpit works pretty much the same; you just define a new method with different parameters. You cannotjust change the return type, though. The parameters to the methods must be different in order to overload one. Hereis an article about overloading vs. overriding in Java.
正如评论和其他答案中所述,您可以在子类中定义一个与其超类中的方法同名的方法,但您不能完全覆盖它。这两种方法仍然存在,因此称为重载。在Java和C Sharp 中,它的工作原理几乎相同;您只需定义一个具有不同参数的新方法。但是,您不能只更改返回类型。方法的参数必须不同才能重载一个。这是一篇关于 Java 中重载与覆盖的文章。