派生类中是否可以使用静态方法和变量?
我在类中有静态变量和方法。它们是否会在派生类中继承?
例如:
class A
{
public static int x;
public static void m1()
{
some code
}
}
class B:A
{
B b=new B();
b.m1(); // will it be correct or not, or will I have to write
// new public voim1(); or public void m1();
b.x=20; // will it be correct or not?
}
I have static variables and methods in a class. Will they be inherited in derived classes or not?
For example:
class A
{
public static int x;
public static void m1()
{
some code
}
}
class B:A
{
B b=new B();
b.m1(); // will it be correct or not, or will I have to write
// new public voim1(); or public void m1();
b.x=20; // will it be correct or not?
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
静态成员将在派生类中可用,但无法使用实例引用访问它们。您可以直接访问它们:
或者使用类的名称:
The static members will be available in the derived class, but you can't access them using an instance reference. Either you access them directly:
or by using the name of the class:
静态成员将可用,但您将无法在实例上引用它们。相反,使用类型进行引用。
例如
The static members will be available, but you won't be able to reference them on the instance. Instead, reference using the type.
E.g.
静态成员可用,但您无法在实例上引用它们。因此,您必须使用超类的类前缀。
A.m1()
。这与 Java 语言形成鲜明对比,在 Java 语言中,您可以使用实例引用访问静态方法和字段。
Static members are available, but you won't be able to reference them on the instance. Hence you must use the class prefix of the superclass.
A.m1()
.This is in direct contrast to the Java language where you can access static methods and fields using instance references.
静态成员不与实例关联,因为它是类变量或类方法,您可以使用类名访问它。它通常用于保留一般类信息,例如创建的实例数量等。
A static member is not associated with an instance because its a Class variable or a Class method, you can access it using the class name. It is usually used to retain general Class information for example number of instances created and etc.