Inherit a static variable in Java

I want to have the following setting:

abstract class Parent { public static String ACONSTANT; // I'd use abstract here if it was allowed // Other stuff follows } class Child extends Parent { public static String ACONSTANT = "some value"; // etc } 

Is this possible in java? How? I would prefer not to use instance variables / methods if I can avoid this.

Thanks!

EDIT:

Constant is the name of the database table. Each child object is a mini ORM.

+4
source share
2 answers

you cannot do it exactly as you want. Perhaps an acceptable compromise would be:

 abstract class Parent { public abstract String getACONSTANT(); } class Child extends Parent { public static final String ACONSTANT = "some value"; public String getACONSTANT() { return ACONSTANT; } } 
+18
source

In this case, you should remember that in java you cannot overestimate static methods. What happened is to hide the material.

according to the code you supplied, if you follow these steps, the answer will be null

 Parent.ACONSTANT == null ; ==> true Parent p = new Parent(); p.ACONSTANT == null ; ==> true Parent c = new Child(); c.ACONSTANT == null ; ==> true 

while you use Parent as a reference type, ACONSTANT will be null.

will allow you to do something like this.

  Child c = new Child(); c.ACONSTANT = "Hi"; Parent p = c; System.out.println(p.ACONSTANT); 

The output will be zero.

+2
source

All Articles