Overriding class data

From: Ovid (publiustemp-googlegroups_at_yahoo.com)
Date: 12/22/03


Date: 21 Dec 2003 17:19:09 -0800

Hi,

I'm trying to determine the cleanest way to override class data in a
subclass.

  class Universe {
    public String name;
    private static double PI = 3.1415;

    Universe(String name) {
      this.name = name;
    }

    public String toString() {
      return "Universe: " + name + " PI: " + PI;
    }
  }

  class UniverseRoman extends Universe {
    private static double PI = 3;

    UniverseRoman(String name) {
      super(name);
    }

    public String toString() {
      return "Universe: " + name + " PI: " + PI;
    }
  }

  class TestUniverse {
    public static void main(String args[]) {
      Universe bob = new Universe("Bob");
      UniverseRoman ovid = new UniverseRoman("Ovid");
      System.out.println(bob);
      System.out.println(ovid);
    }
  }

>From what I can tell, if I want to override a class variable in a
subclass, I have to duplicate all methods that access the class
variable. If I want to be able to change the class data:

  public static void setPI(double pi) {
    PI = pi;
  }

If I just provide that in my Universe class, calling
UniverseRoman.setPI(4) will set the Universe class PI to 4, not the
roman value of pi. Duplicating that method in UniverseRoman seems to
be the answer, but part of the value of OO is that, in theory, we
shouldn't have to duplicate this much code. What am I missing?

Cheers,
Ovid