OPK
OPK

Reputation: 4180

Redefine static members in a derived class. Java

So i was reading the book and the author says " The static members aren't involved in runtime polymorphism. You can't override the static members in a derived class, but you can redefine them."

What is that mean? Can you give me a example for this also?

Thank you.

Upvotes: 0

Views: 431

Answers (4)

Alexander
Alexander

Reputation: 48262

You can see for yourself with this

class A {

    static int x = 1;
    int y = 1;

    int f() {
        return 1;
    }

    static int sf() {
        return 1;
    }
}

class B extends A {

    static int x = 2;
    int y = 2;

    int f() {
        return 2;
    }

    static int sf() {
        return 2;
    }

}

public class Test {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        A b = new B();
        System.out.println("A.x=" + ((A) b).x);
        System.out.println("B.x=" + b.x);
        System.out.println("A.y=" + ((A) b).y);
        System.out.println("B.y=" + b.y);
        System.out.println("A.f() = " + ((A) b).f());
        System.out.println("B.f() = " + b.f());
        System.out.println("A.sf() = " + ((A) b).sf());
        System.out.println("B.sf() = " + b.sf());

    }

}

It pprints:

A.x=1 B.x=1 A.y=1 B.y=1 A.f() = 2 B.f() = 2 A.sf() = 1 B.sf() = 1

One would expect B.sf to be printed as 2 but no.

Same one would expect B.x and B.y printed as 2 but also no because fields are also not polymorphic, only functions.

I'm not sure if this has much practical value, one surely learns that after having done an error. This is likely to be asked at worse job interviews though.

Upvotes: 1

Eran
Eran

Reputation: 393836

If you re-define a static member (either method or variable) in a sub-class, you are hiding the definition of the super-class.

public class Super
{
    public static void methodA()
    {

    }
}

public class Sub extends Super
{
    public static void methodA()
    {

    }
}

Here static methodA is redefined in the sub-class, but it doesn't override the methodA of the super class.

Calling Sub.methodA would invoke Sub's methodA. If Sub didn't have a methodA, calling Sub.methodA would have called Super's methodA.

Upvotes: 4

SMA
SMA

Reputation: 37023

If you redefine static method in subclass, its called method hiding. Static method are resolved at compile time rather than run time, and you call them based on class like say:

class A {
    public static void mymthod() {}
}

class B extends A {
    public static void mymthod() {}
}

And you call as:

A a = new B();
a.mymthod();//resolved at compile time and associated with class A (compiler will warn although as static method doesnt necessarily need an object to call)

Upvotes: 1

user4380034
user4380034

Reputation:

The variable in subclass hides the variable, with the same name, in the super class.

Upvotes: 0

Related Questions