JAVA question....

gopunk

Lifer
Jul 7, 2001
29,239
2
0
if i have an abstract class, and define a variable "value" to be of type Object, then in the constructor of a subclass assign "value" to be something like Integer(4), is there any way i can use the Integer class methods with value? right now i have resorted to typecasting like so:

((Integer)value).intValue()

but i am wondering if there is some more official way... some way that makes "value" an Integer instead of an Object.

going to go eat dinner, look forward to your advice...

thanks :)
 

skriefal

Golden Member
Apr 10, 2000
1,418
3
81
If the variable is declared in the superclass as an instance of java.lang.Object, then you must cast to java.lang.Integer to access the Integer class methods.

However, if you're going to have multiple subclasses that hold references to different types of objects then I suggest that you don't place the reference in the superclass. Instead, each subclass should have a reference to an instance of the appropriate object class and then the methods within the subclass can operate directly on the variable (without casting) since they'll know that the reference is to an instance of the appropriate type or a subclass thereof. If the superclass needs to contain methods that operate on the variable, then the appropriate pieces can be pulled out and replaced with abstract template methods that you can then implement within each subclass.

Also, you'd get more responses to this thread in the "Software/Programming" forum...
 

gopunk

Lifer
Jul 7, 2001
29,239
2
0
Originally posted by: skriefal
If the variable is declared in the superclass as an instance of java.lang.Object, then you must cast to java.lang.Integer to access the Integer class methods.

However, if you're going to have multiple subclasses that hold references to different types of objects then I suggest that you don't place the reference in the superclass. Instead, each subclass should have a reference to an instance of the appropriate object class and then the methods within the subclass can operate directly on the variable (without casting) since they'll know that the reference is to an instance of the appropriate type or a subclass thereof. If the superclass needs to contain methods that operate on the variable, then the appropriate pieces can be pulled out and replaced with abstract template methods that you can then implement within each subclass.

Also, you'd get more responses to this thread in the "Software/Programming" forum...

hmm ok, i think you are right. thanks :)