Logo 
Search:

Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

instantaite objects from frequently called static methods

  Asked By: Violet    Date: Oct 22    Category: Java    Views: 647
  

If you instantiate an object of another class from a static method,
Will that object be overridden each time the static method is called?

What will happen?

or should the object be instantiated outside of the static class so
it is only instantiated once.

Share: 

 

4 Answers Found

 
Answer #1    Answered By: Tommy Thompson     Answered On: Oct 22

Can you give an example of some code which you think would demonstrate
this situation?

 
Answer #2    Answered By: Adelmo Fischer     Answered On: Oct 22

Anyway, I was wandering if anyone in here has completed a program
similar to the one we are doing at the moment.

The program must simulate the life generation of a colony of cells,
one of our teachers said it is commonly called "Life", if anyone here
has done it, I was wandering if they'd like to upload it so I could
have a gander.

 
Answer #3    Answered By: Mansur Bashara     Answered On: Oct 22

A non-static variable describes a property of a particular object, while a
static variable describe a property of the entire class. That's the whole thing
you must keep in mind.

Example: Let's imagine the class  of all pens of a given color.

public class SameColorPen
{
private static  String color = "red"; // this will be the same for all the
objects
private int size; // this will be different for all the objects

public SameColorPen(int size)
{
this.size = size;
}

public static String paint(String newColor)
{
String oldColor = color;
color = newColor;
return oldColor;
}
}

SameColorPen pen1(10); // red pen of size 10
SameColorPen pen2(20); // red pen of size 20
String oldCol = SameColorPen.paint("blue"); // this paints all the objects  of
this class in blue. pen1 and pen2 will be blue from now on.
SameColorPen pen3(30); // blue pen of size 30

Now take a closer look at the paint method  body. Inside a static method, only
static members of the class can be refered. But you are free to create and use
any other object. In the example, I declared a String object. This object  will
not be over-anything each time  the paint method is called, because it is created
and destroyed with each call, like any variable inside a block.

 
Answer #4    Answered By: Farah Khan     Answered On: Oct 22

Yes, the object  will be overrided if you instantiate an object of another class
from a static  method, actually from all methods.
If you want it stay same over all the instances of the Class, declare a static
varible and instantiate it in the variable declaration.

 
Didn't find what you were looking for? Find more on instantaite objects from frequently called static methods Or get search suggestion and latest updates.