Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

Static class instantiation

  Asked By: Bill    Date: Sep 21    Category: Java    Views: 762

If I have the following code and call method_1 then tmp1 is
instantiated. When method_1 is through tmp1 is destroyed. If I call
method_2 will the newly instantiated class tmp2 refer to the static
class created in method_1 or will it create a new static class?

class a(
public a(){}
void method_1(){b tmp1 = new b();}
void method_2(){b tmp2 = new b();}

class b(
static c tmpc = new c();
public b(){}

class c(
public c(){}



1 Answer Found

Answer #1    Answered By: Calais Bernard     Answered On: Sep 21

tmpc is a static  variable so there is only one copy for all objects
of the c class. Your method_1 and method_2 create  2 objects of
the b class, but each holds a reference to the same object of the
c class. After creating the b objects, try testing to see if they
the same tmpc object:

public class  StaticTest {
public static void  main(String [] args) {
b tmp1 = new b();
b tmp2 = new b();
if(tmp1.tmpc == tmp2.tmpc)
System.out.println("Only one c object");

to see if they are the same object. (Using == will only evaluate
true if the reference variables point to the same object). It prints
that line of course.

Didn't find what you were looking for? Find more on Static class instantiation Or get search suggestion and latest updates.