开发者

Are static methods and variables available in derived classes?

I have static variables and methods in a class. Will they be inherited in der开发者_StackOverflowived 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?
}


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:

m1();
x = 20;

or by using the name of the class:

A.m1();
A.x = 20;


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.

class B:A
{
    public void Foo()
    {
        A.m1();
        A.x=20;
    }
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜