子类可以覆盖方法并具有不同的参数吗?
Can a subclass override a method and have different parameters?
我想在多个 subclasses 中有一个方法,它基本上完成了某件事(比如获取用户信息),但是在 main [ 中声明(并且具有不同的参数和定义) =14=]。这可能吗?
我知道这并不是真正的压倒一切,但可以这样做吗?或者它不是一种合适的构造方法的方式吗?
你想做的事情叫做重载一个方法。这是可行的,而且经常发生。 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"));
}
}
您可以拥有同名但参数数量不同的方法的多个版本。您可以将所有这些都放在 main/parent class 中,或者您可以只在子 class 中添加较新的版本。这样做没有限制。
如评论和其他答案中所述,您可以在子类中定义一个与其超类中的方法同名的方法,但您不能完全覆盖它。这两种方法仍然存在,所以它被称为重载。 Java and in C Sharp it works pretty much the same; you just define a new method with different parameters. You cannot just change the return type, though. The parameters to the methods must be different in order to overload one. Here 中有一篇关于 Java 中重载与覆盖的文章。
我想在多个 subclasses 中有一个方法,它基本上完成了某件事(比如获取用户信息),但是在 main [ 中声明(并且具有不同的参数和定义) =14=]。这可能吗?
我知道这并不是真正的压倒一切,但可以这样做吗?或者它不是一种合适的构造方法的方式吗?
你想做的事情叫做重载一个方法。这是可行的,而且经常发生。 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"));
}
}
您可以拥有同名但参数数量不同的方法的多个版本。您可以将所有这些都放在 main/parent class 中,或者您可以只在子 class 中添加较新的版本。这样做没有限制。
如评论和其他答案中所述,您可以在子类中定义一个与其超类中的方法同名的方法,但您不能完全覆盖它。这两种方法仍然存在,所以它被称为重载。 Java and in C Sharp it works pretty much the same; you just define a new method with different parameters. You cannot just change the return type, though. The parameters to the methods must be different in order to overload one. Here 中有一篇关于 Java 中重载与覆盖的文章。