简体   繁体   English

Java中等效的VB“ Shadow”或C#“ new”关键字是什么?

[英]What is the VB “Shadow” or C# “new” keyword Equivalent in Java?

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. 当我想定义非虚方法的新实现时,可以在C#中使用new关键字,在VB中使用shadow关键字。 For example: 例如:

C# code: C#代码:

public class Animal
{
    public void MyMethod()
    {
        //Do some thing
    }
}

public class Cat : Animal
{
    public new void MyMethod()
    {
        //Do some other thing
    }
}

VB code: 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

Now, my question is: 现在,我的问题是:

What is the VB Shadow (or C# new ) keyword equivalent in Java ? Java中等效的VB Shadow (或C# new )关键字是什么?

The primary answer to your question is probably "There is none." 您问题的主要答案可能是“没有答案”。 Details: 细节:

Java's methods are "virtual" (in C# terminology) by default; Java的方法默认为“虚拟”(用C#术语); 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. 在定义覆盖时,使用@Override注释很有用(但不是必需的 ),以便编译器会在您认为自己没有覆盖时警告您,以便阅读代码(和JavaDoc)的人知道您的意思。在做。

Eg: 例如:

class Parent {
    public void method() {
    }
}
class Child extends Parent {
    @Override
    public void method() {
    }
}

Note that there's no special keyword on method in Parent . 请注意, Parent method中没有特殊的关键字。

If a Java method is marked final (non-virtual, the C# default), you can't override it at all. 如果将Java方法标记为final (非虚拟,默认为C#),则无法覆盖它。 There is no equivalent to C#'s new in that context. 在这种情况下,没有C#的new Eg: 例如:

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)
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM