1

I wrote something like this:

public abstract class A {
    static String name = "A";

    public static String getName() {
        return this.name;
    }
}

public class B extends A {
    static String name = "B";
}

public class C extends A {
    static String name = "C";
}

When I call B b = new B(); System.out.println(b.getName()); (better of course System.out.println(B.getName());) I get A, not B (same for C).

I don't get why. Can someone give me a handwave?


Thanks for the answer!

But how would I do something like that?

In my case I want to make a URL Manager. The variable contains a Pattern, the method tests for a given String, if the Pattern matches.

Every class extending A has to have the Pattern and uses the same Method to test if it matches. It should be static too, because I only want to instantiate, if the Pattern matches.

3244611user
  • 224
  • 2
  • 10
  • Read this http://stackoverflow.com/questions/24719880/why-can-we-reduce-visibility-of-a-property-in-extended-class/24719892#24719892 – Unihedron Aug 16 '14 at 12:05

1 Answers1

4

There is no polymorphism for static members and no polymorphism of data members. Polymorphism exists only for instance (non-static) methods. Your static getName() method is defined in A and returns the value of the static member defined in A.

Anyway, you shouldn't access static methods via an instance, since it's confusing. Use A.getName().

Eran
  • 387,369
  • 54
  • 702
  • 768