是否有一个Java等同于C#的“新静态”或“静态新”?

时间:2011-07-01 19:28:31

标签: java

Java是否等同于C#的new Modifier

5 个答案:

答案 0 :(得分:2)

没有。对于静态方法,它们不是在Java中继承的,因此您不需要等效的new修饰符。

答案 1 :(得分:2)

Java中没有类似的构造。

(不要将new@Override的反面混淆。事实并非如此。)

考虑这个C#代码:

class A {
    virtual public int x() { return 1; }
    virtual public int y() { return 1; }
}

class B : A {
    new public int x() { return 2; }
    override public int y() { return 2; }
}

void Main()
{
    A aa = new A();
    A ba = new B(); // compile time type of ba is A
    B bb = new B(); // compile time type of bb is B

    aa.x().Dump();
    ba.x().Dump(); // look how this is really A.x!!
    bb.x().Dump();

    "---".Dump();

    aa.y().Dump();
    ba.y().Dump(); // this is B.y!
    bb.y().Dump();
}

在LINQPad中运行时,会生成:

1
1
2
---
1
2
2

注意编译时类型如何确定调用哪个方法,这会受到使用newoverride修饰符的影响。 new修饰符本质上是为给定成员引入了由编译时类型确定的分支。它可以用于强大的力量......而且功能强大带来了更多的陈词滥调。

快乐的编码。

答案 2 :(得分:1)

没有。 http://download.oracle.com/javase/tutorial/java/IandI/hidevariables.html

您可以使用基于APT的工具链执行此操作。定义注释,并在没有注释的情况下检测字段隐藏的情况。

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD})
public @interface HideSuper { }

然后在你的代码中

public class Parent {
   Object x;
}

public class GoodChild extends Parent {
   @HideSuper Object x; 
}

public class TroublingChild extends Parent {
   Object x; // your plugin should raise warnings here
}

[回复后编辑]:

1 - 请注意,虽然提到的@Overridenew具有紧密的语义,但它不能统一应用于类成员

2 - 关于上述建议,将保留范围缩小到Class或甚至Source可能更为正确。

3 - 最后,IDE应支持基于APT的方法。 Eclipse以某种方式支持它。

答案 3 :(得分:0)

我认为您正在寻找的等价物可能是@Override注释。它为编译器提供了一个提示,您打算从父级覆盖方法。 Java对象中的所有方法都是“虚拟的”,就像你必须在C ++中定义一样,并且可以为多态行为重写。

public class Car {
    public void start() { ...
    }
}

public class Ferrari {
    @Override
    public void start() {
    }
}

使用@Override,如果您更改Car.start()签名并且不更改Ferrari.start()以匹配,编译器将会出错。

答案 4 :(得分:0)

没有。

在Java中,子类将覆盖或隐藏同名的超类成员(字段,方法,类型)。隐藏永远不会发出警告,因此不需要修饰符来抑制警告。