当我想定义非虚拟方法的新实现时,我可以在C#中使用new关键字或在VB中使用shadow关键字。 例如:
C#代码:
public class Animal { public void MyMethod() { //Do some thing } } public class Cat : Animal { public new void MyMethod() { //Do some other thing } }VB代码:
Public Class Animal Public Sub MyMethod() 'Do some thing End Sub End Class Public Class Cat Inherits Animal Public Shadows Sub MyMethod() 'Do some other thing End Sub End Class现在,我的问题是:
在Java中,什么是VB Shadow (或C# new )等效关键字?
When I want to define a new implementation of a non virtual method, then I could to use new keyword in C# or shadow keyword in VB. For example:
C# code:
public class Animal { public void MyMethod() { //Do some thing } } public class Cat : Animal { public new void MyMethod() { //Do some other thing } }VB code:
Public Class Animal Public Sub MyMethod() 'Do some thing End Sub End Class Public Class Cat Inherits Animal Public Shadows Sub MyMethod() 'Do some other thing End Sub End ClassNow, my question is:
What is the VB Shadow (or C# new) keyword equivalent in Java ?
最满意答案
你的问题的主要答案可能是“没有。” 细节:
Java的方法默认是“虚拟的”(在C#术语中); 它们可以在子类中重写。 原始方法不需要特殊关键字。 定义重写时,使用@Override注释是有用的(但不是必需的 ),以便编译器会在你不认为自己是重写时警告你,因此读取代码(和JavaDoc)的人知道你'干嘛。
例如:
class Parent { public void method() { } } class Child extends Parent { @Override public void method() { } }请注意, Parent method没有特殊关键字。
如果Java方法被标记为final (非虚拟的,C#默认值),则根本无法覆盖它。 在这种情况下,没有相当于C#的new 。 例如:
class Parent { public final void method() { } } class Child extends Parent { @Override // <== Won't compile, you simply can't override public void method() { // <== final methods at all (even if you added // <== "final" to the declaration) } }The primary answer to your question is probably "There is none." Details:
Java's methods are "virtual" (in C# terminology) by default; they can be overridden in subclasses. No special keyword is required on the original method. When defining the override, it's useful (but not required) to use the @Override annotation so that the compiler will warn you if you're not overriding when you think you are, and so people reading the code (and JavaDoc) know what you're doing.
E.g.:
class Parent { public void method() { } } class Child extends Parent { @Override public void method() { } }Note that there's no special keyword on method in Parent.
If a Java method is marked final (non-virtual, the C# default), you can't override it at all. There is no equivalent to C#'s new in that context. E.g.:
class Parent { public final void method() { } } class Child extends Parent { @Override // <== Won't compile, you simply can't override public void method() { // <== final methods at all (even if you added // <== "final" to the declaration) } }更多推荐
发布评论