Jump to content

  • Log In with Google      Sign In   
  • Create Account

FREE SOFTWARE GIVEAWAY

We have 4 x Pro Licences (valued at $59 each) for 2d modular animation software Spriter to give away in this Thursday's GDNet Direct email newsletter.


Read more in this forum topic or make sure you're signed up (from the right-hand sidebar on the homepage) and read Thursday's newsletter to get in the running!


[java] Class Variables


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
13 replies to this topic

#1 Wrathnut   Members   -  Reputation: 400

Like
Likes
Like

Posted 05 September 2000 - 09:41 AM

I''ve got a fairly stupid question here about class variables.. Suppose I''m writing an applet/application that looks something like this.. public class applet extends Applet{ public void init(){ myClass.var1 = new int[10]; for(int j = 0; j < 10; j++){ myClass.var1[j] = j; } } } public class myClass{ public static int var1[]; //Most methods of this class will use var1[]; } This seems fairly sloppy to me, I mean the class myClass should handle all of it''s own variables. And although you can assign the values to var1[] in the myClass constructor, every time you create an object of type myClass it will try and run through the for loop to assign vars(even if var1[] is static the loop still exists), which could waste alot of time if you had a big loop, or a lot of objects of type myClass. And that seems even sloppier to me... anyway my question is this: Is there a method you can override somewhere or is there some technique you could use to assign values to a class variable like var1[], that gets run only once, like when the class is initially loaded? War doesn't determine who is right, war determines who is left.

Sponsor:

#2 felonius   Members   -  Reputation: 122

Like
Likes
Like

Posted 05 September 2000 - 10:27 AM

Assuming you are using Java 1.1 or later then you can use static blocks like this:

public class myClass{

private static int var1[];

static
{
var1 = new int[10];
for(int j = 0; j < 10; j++)
{
var1[j] = j;
}
}

//Most methods of this class will use var1[];
}

the static block will be run when the class is loaded and never again. So as you see I have changed var1 to be private because your main class no longer need to access it.

Jacob Marner





#3 SteveMeister   Members   -  Reputation: 122

Like
Likes
Like

Posted 06 September 2000 - 01:13 AM

But even so, this is still not very OO. A better OO approach would be to use a singleton class:

public class MyClass
{
private static MyClass instance = new MyClass();

private int var1[];

private MyClass()
{
var1 = new int[10];
for (int j = 0; j < 10; j++)
{
var1[j] = j;
}
}

public static int getElement(int index)
{
return instance.var1[index];
}
}

You should probably throw ArrayIndexOutOfBoundsException from getElement, or at least check "index".

Anyway in your applet, you just call

int value = MyClass.getElement(index);

Either way will work, but the singleton pattern is better object oriented programming.


#4 felonius   Members   -  Reputation: 122

Like
Likes
Like

Posted 06 September 2000 - 03:01 AM

SteveMeister:

The singleton class solves the general problem of making sure that only one instance is available of a class and that it always is available.

This does not solve problem at hand which is that MyClass has multiple instances that must use some of the same data.
Singleton variables solve another problem.

You cannot say that singletons are more OO than class variables. That would be like comparing apples and bananas. And even if we could compare them class variables are very central to OO. In the original OO languages like Simula or SmallTalk class variables played a very central part.

In fact in your sample you still use class variables. Writing

class MyClass
{
private static MyClass instance = new MyClass();
}

is not different from:

class MyClass
{
private static MyClass instance;

static
{
instance = new MyClass();
}
}

The only thing that has happened compared to the code I suggested is that you have encapsulated the array in the class and thereby preventing you from adding other data members to MyClass.

Jacob Marner

#5 Jim_Ross   Members   -  Reputation: 122

Like
Likes
Like

Posted 06 September 2000 - 03:24 AM

If you only want the code run once per program session, use the singleton class stevemeister mentioned. If you want it run every time you create an object of that type, put the code in the constructor. There are a few more techniques but i doubt they are required for this situation. Perhaps making the array it's own singleton class would be the best approach. If you try to make it a static variable of class MyClass, you will need to check whether the variable is initialized at every class instantiation. But if you make the array its own singleton class, your methods inside MyClass can access it without worry of whether it's instantiated or not.


    
class MyClass {

method() {
int count = SingleArray.getArray().count();
}

}

class SingleArray {

private var1[];
private static SingleArray inst = new SingleArray();

public SingleArray() {
//init var1[];

}

public static getArray() {
return inst;
}

public count() {
//...

}
}


Edited by - Jim_Ross on September 6, 2000 10:25:03 AM

#6 Wrathnut   Members   -  Reputation: 400

Like
Likes
Like

Posted 06 September 2000 - 05:32 AM

Looking at your guy''s suggestions I was able to find something about the static initializer in my java book, unless my understanding is wrong it appears that the static{} code block only gets run when the class is initially loaded not everytime a variable of type myClass is created, Am I wrong? If not this seems to be the most cost effective solution.

Although I can''t find anything in my java book about singleton classes, I''m wondering if you guys know a place on the net I could bone up on this... Also are singleton classes just a different name for dynamic class loading?

Anyway thanks for all of the insightful posts. I thought I was alittle more than just a newbie but it seems I''ve proved myself wrong once again! ^_^

War doesn't determine who is right, war determines who is left.

#7 Anonymous Poster_Anonymous Poster_*   Guests   -  Reputation:

Likes

Posted 06 September 2000 - 07:54 AM

quote:
Original post by felonius

SteveMeister:

The singleton class solves the general problem of making sure that only one instance is available of a class and that it always is available.

This does not solve problem at hand which is that MyClass has multiple instances that must use some of the same data.
Singleton variables solve another problem.

You cannot say that singletons are more OO than class variables. That would be like comparing apples and bananas. And even if we could compare them class variables are very central to OO. In the original OO languages like Simula or SmallTalk class variables played a very central part.

In fact in your sample you still use class variables. Writing

class MyClass
{
private static MyClass instance = new MyClass();
}

is not different from:

class MyClass
{
private static MyClass instance;

static
{
instance = new MyClass();
}
}

The only thing that has happened compared to the code I suggested is that you have encapsulated the array in the class and thereby preventing you from adding other data members to MyClass.

Jacob Marner


But it''s "bad" to expose class variables to the outside world. You should only provide access to class variables via method calls, and class variables should be private, except for constant values.

That way you can alter the functionality and/or contents of the class, and as long as you don''t change the methods, you don''t break any code that USES the class. You also enforce the black-box nature of the class, because clients of the class neither know nor care about the inner workings of the class, just about what the interface to the class is (the methods).

So it''s not that class variables should not be used at all, it''s that they should not be made public.

Oh and Wrathnut, the Singleton is a Design Pattern. Here''s an article that describes it and how it''s implemented in Java.
http://members.tripod.com/rwald/java/articles/Singleton_in_Java.html



#8 felonius   Members   -  Reputation: 122

Like
Likes
Like

Posted 06 September 2000 - 10:27 AM

quote:

But it''s "bad" to expose class variables to the outside world. You should only provide access to class variables via method calls, and class variables should be private, except for constant values.

That way you can alter the functionality and/or contents of the class, and as long as you don''t change the methods, you don''t break any code that USES the class. You also enforce the black-box nature of the class, because clients of the class neither know nor care about the inner workings of the class, just about what the interface to the class is (the methods).



It is not any worse to expose class variables than it is to expose instance variables. If you should follow that principle fully you should never have any public data members but always access them through getter and setter methods. The old languages like Smalltalk-80 didn''t even have public datamembers. Every datamember was protected always.

Actually, now that I come to think about it, what do we mean about more or less OO? It is a rather subjective concept, isn''t it? I think we could bicker endlessly here without ever getting any solution.
It doesn''t really matter whether it is more OO or less OO. What matters is whether the implementation does the job and is so modular that it promotes reuse in the most optimal way. If that is OO, then OO is worth striving for.

Jacob Marner

#9 CodyVa   Members   -  Reputation: 122

Like
Likes
Like

Posted 06 September 2000 - 04:02 PM

Am I missing somethign what''s a singleton class? does this mean the class can only be loaded once?(correct term?)


how can you make a reference to the a class within the class
class whatever { whatever inst = new whatever(); }

does it have to be static?

when the static whatever class is made it doesn''t need to make another whatever cause it(the static class) is already made??


but are you allowed to make a non-static class in the same class?

I dont'' get it.

#10 joeG   Members   -  Reputation: 172

Like
Likes
Like

Posted 06 September 2000 - 05:58 PM

A singleton class is a class where only one object of the class type is instantiated throughout the life of the program. It is useful for dynamic loading of classes, because the class takes care of the loading for you or delegates it to a seperate class (usually termed a factory). You can only access new libraries through this one object.


joeG



#11 TheEarl   Members   -  Reputation: 122

Like
Likes
Like

Posted 10 September 2000 - 08:30 PM

To clarify that a little:

A singleton class is a class with a static getter which will return a single instance of a class, every class which calls that static method, will receive a reference to that one instance of a class.
The purpose of a singleton class, is to prevent the use of Global variables.
For example, Runtime.getRuntime() in Java, is an example of a singleton class.

Singleton classes and other similar concepts, are detailed in a book called "Design Patterns".

Happy Coding

#12 Hitman   Members   -  Reputation: 122

Like
Likes
Like

Posted 14 September 2000 - 05:33 PM

This is in regards to the public vs private class variables. I don't see the difference in making a variable public, or making it private and creating a get/set method. Both are bad in my opinion. As an example: (this example is in no way complete, just using it as an example)

this:
            
class Sprite
{
private int x;
private int y;

void setX(int x)
{
this.x = x;
}
}

is really no different from this:


class Sprite
{
public int x;
public int y;
}


The whole point behind encapsulation is to seperate the interface from the implementation. In the above examples if we wanted to all of a sudden change the coordinate system from int to long, we would have the same problem with all calling code. Either we search for every reference to Sprite.x, or we search for every reference to Sprite.setX.

Bret.

Edited by - Hitman on September 14, 2000 12:35:02 AM

Edited by - Hitman on September 14, 2000 12:35:33 AM

#13 felonius   Members   -  Reputation: 122

Like
Likes
Like

Posted 14 September 2000 - 11:19 PM

Well one point of using public setters is if we want to change the internal representation without changing any code.

lets say that x,y was realtive coordinates of some kind. If I changed them to be absolute coordinates the old code would break. I could now change setX and setY to take this into acount (by adding origin) and mae a setAbsX and setAbsY for setting the absolutes directly. This way code clients that otherwise would have been broken now still works.

Or lets say that x,y, suddenly where to be stored in a C++ program instead. Again setX and setY could be changed to calling native data while by using x and y directly all your code using x and y would have to be rewritten.

------------

TheEarl,
true, "Design patterns" use a getInstance() variable to retrieve the isntance, but by using a class variable you achieve them same thing - so whats the difference? It is still a singleton.

Jacob Marner


#14 SteveMeister   Members   -  Reputation: 122

Like
Likes
Like

Posted 15 September 2000 - 01:03 AM

If you make your class variables private and provide set and get methods for them, these variables are now considered "properties" and you can use JavaBeans introspection to obtain the property names, and to get and set their values.

This makes it easier to implement a pluggable, extensible architecture.

Of course, as felonius said, hiding the internal representation of the properties is another real benefit.





Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS