Overriding Static Variables When Subclassing

Overriding static variables when subclassing

Use a virtual method to get a reference to the static variable.

class Base {
private:
static A *a;
public:
A* GetA() {
return a;
}
};

class Derived: public Base {
private:
static B *b;
public:
A* GetA() {
return b;
}
};

Notice that B derives from A here. Then:

void Derived::paint() {
this->GetA() ...
}

Java static variable in method overriding

Static variables are not inherited in java. You varibale static String a is static which associates it to a class. Java inheritance doesn't work with static variables.

If you absolutely want the superclass variable you could use:

System.out.println(super.a);

Here is the inheritance what you probably wish to see:

abstract class A {
String a = "superclass";

abstract void test();
}

class B extends A {
void test() {
System.out.println(a); // Output superclass
}
}

I remove the static identifier and removed the subclass's implementation of variable a. If you run this you'll get superclass as output.

overriding static vars in subclasses swift 1.2

The documentation says:


static
” methods and properties are now allowed in classes (as an alias for “
class final
”).

So it is final, which means you cannot override it.

java overriding static fields

It seems that you're confused with the concept of Overriding.

in Java, as far as class variables are concerned, you do not override them, you hide them.

Overriding is for instance methods. Hiding is for instance variables.

Both Hiding and Overriding are different.



Related Topics



Leave a reply



Submit