Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Westi on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

does explicit upcasting save memory space?

Status
Not open for further replies.

carpeliam

Programmer
Mar 17, 2000
990
US
i've got a subclass of something that carries a lot more information than the superclass. if i explicitly upcast an object of the subclass, will it still retain the information from the superclass? i'm looking to save memory.. and if i don't need everything from the superclass, i'd rather not return an object of superclass if i don't have to.

Liam Morley
lmorley@wpi.edu
"light the deep, and bring silence to the world.
light the world, and bring depth to the silence."
 
An object by itself hardly takes any memory. It's the objects that the class holds that take up space.

I did some experiments with JDevelopers "Memory Profiler", and I didn't see where casting affected the memory used except in those cases where I also used different constructors that did not create unnecessary class objects.

Try to avoid having objects initialized on a class level in the subclass:

Code:
Class Foo()
{
   Long x = new Long(1);

   public Foo()
   {
   }
}

Instead do this:

Class Foo()
{
   Long x = null;

   public Foo()
   {
      x = new Long(1);
   }
}

then arrange it so the subclass constructor does not get called.

As a side note, for a small program casting actually increases memory usage because of the additional ClassCastExceptions, etc that java brings in.
 
I don't think upcasting/downcasting changes anything of your object. (You can always cast it back, and you'll get all the info).

Maybe it is better to use composition instead of inheritence.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top