views:

123

answers:

2

I want to have the following setup:

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'd rather not use instance variables/methods if I can avoid it.

Thanks!

EDIT:

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

+4  A: 

you can't 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; }
}
stew
That's great! Thanks!
SapphireSun
+1  A: 

In this case you have to remember is in java you can't overried static methods. What happened is it's hide the stuff.

according to the code you have put if you do the following things answer will be null

Parent.ACONSTANT == null ; ==> true

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

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

as long as you use Parent as reference type ACONSTANT will be null.

let's you do something like this.

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

Output will be null.

asela38
Whoa, cool example. Thanks for taking the time to post that :-) +1
SapphireSun