[英]Java - Is there Java equivalent for C# new keyword in method signature? How I can replace final methods in Java?
As you maybe know, as Java language perspective all method in C# are final by default (also vice versa, all methods in Java are virtual as C# language perspective). 您可能知道,作为Java语言透视图,C#中的所有方法都是默认的最终方法(反之亦然,Java中的所有方法都是虚拟的C#语言透视图)。
In C# we can replace final (non-virtual) methods by new
keyword ( please see this ). 在C#中,我们可以用
new
关键字替换final(非虚拟)方法( 请参阅此内容 )。 There is not anyway to replace final methods in Java? 无论如何都无法替换Java中的最终方法?
Edit 1: 编辑1:
I just want to mention that method replacing is not same with method overriding. 我只想提一下方法替换与方法覆盖不一样。 Please run this C# code:
请运行此C#代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ComapreOverrideWithNew
{
class Program
{
static void Main(string[] args)
{
var cat = new Cat();
cat.PrintNameByNew();
Console.WriteLine(cat.GetNameByNew());
cat.PrintNameByOverride();
Console.WriteLine(cat.GetNameByOverride());
Console.ReadKey();
}
}
class Animal
{
public String GetNameByNew()
{
return "Animal";
}
public void PrintNameByNew()
{
Console.WriteLine(GetNameByNew());
}
public virtual String GetNameByOverride()
{
return "Animal";
}
public void PrintNameByOverride()
{
Console.WriteLine(GetNameByOverride());
}
}
class Cat : Animal
{
new public String GetNameByNew()
{
return "Cat";
}
public override String GetNameByOverride()
{
return "Cat";
}
}
}
For example http://docs.oracle.com/javase/tutorial/java/IandI/final.html is just talking about overriding. 例如http://docs.oracle.com/javase/tutorial/java/IandI/final.html就是在谈论覆盖。 Also this code have not any compiler warning on compilation.
此代码在编译时也没有任何编译器警告。
您不能用Java替换final方法。
There's no such thing in Java . Java中没有这样的东西 。 A final method cannot be overridden.
最终方法无法覆盖。
C#中的所有new
关键字都会抑制编译器警告。
The only way to create a "new" final method in java is if the method is marked private. 在java中创建“新”最终方法的唯一方法是将该方法标记为私有。 The following is legal:
以下是合法的:
public class A
{
private final void go(){};
}
class B extends A
{
private final void go() {};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.