[4743] in java-interest
Re: HELP - need abstract static variables (no good solution?)
daemon@ATHENA.MIT.EDU (Gary Aitken)
Fri Jan 12 05:18:53 1996
Date: Fri, 12 Jan 1996 01:16:59 -0700
From: Gary Aitken <garya@DreamChaser.org>
To: ranlevy@eandm.co.il (Ran Levy - Software), java-interest@java.Eng.Sun.COM
In-Reply-To: <9601111818.AA11986@draven.Eng.Sun.COM>
>Can anybody think of a good solution for the following scenario, or maybe
>explain the rational behind prohibiting abstract static variables in Java??
>
>Static variables declared in some Java class cannot be declared abstract.
>
>The following scenario cannot be solved without redundant duplication of
>part of the code, because of Java (artificial?) limitation.
>
>I have a class (GeneralClass) that defines general methods for a group
>of other classes derived from it (I omit the constructors in this example):
>
> public class GeneralClass {
> static int [] dataVar = null;
> static int infoVar = null;
>
> void printData () {
> // print values from dataVar, uses infoVar
> }
>
> int [] readData (String filename) {
> // also modifies the variable infoVar
> }
> }
>
> public class SubClassOne extends GeneralClass {
> }
>
> public class SubClassTwo extends GeneralClass {
> }
>
>The problem is that in this code all instances of GeneralClass,
>SubClassOne, and SubClassTwo share the same value of dataVar. However,
>according to the required design, SubClassOne and SubClassTwo should
>only differ by the value of dataVar. Also, the dataVar value MUST be
>common for all instances of SubClassOne, and I'd therefore like to
>initialize it in a static block of code.
>
>Notice that the code to read the data from the file is common to all
>subclasses, and therefore resides in GeneralClass.
...
You can solve this problem by using static variables in the derived classes,
but referencing them via an overridden function.
public class GeneralClass {
abstract int infoVarValue();
etc.
void printData () {
// print values from dataVar, uses infoVarValue() & dataVarValue()
}
int [] readData (String filename) {
// also modifies the variable infoVar
}
}
public class SubClassOne extends GeneralClass {
static int [] dataVar = SubClassOneData;
static int infoVar = SubClassOneInfo;
int infoVarValue() { return(infoVar); }
etc.
}
public class SubClassTwo extends GeneralClass {
static int [] dataVar = SubClassTwoData;
static int infoVar = SubClassTwoInfo;
int infoVarValue() { return(infoVar); }
etc.
}
Gary Aitken garya@DreamChaser.org
-
This message was sent to the java-interest mailing list
Info: send 'help' to java-interest-request@java.sun.com