• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.

Archived

This topic is now archived and is closed to further replies.

Wrathnut

[java] Class Variables

13 posts in this topic

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.
0

Share this post


Link to post
Share on other sites
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



0

Share this post


Link to post
Share on other sites
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.
0

Share this post


Link to post
Share on other sites
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
0

Share this post


Link to post
Share on other sites
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
0

Share this post


Link to post
Share on other sites
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.
0

Share this post


Link to post
Share on other sites
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

0

Share this post


Link to post
Share on other sites
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
0

Share this post


Link to post
Share on other sites
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.
0

Share this post


Link to post
Share on other sites
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

0

Share this post


Link to post
Share on other sites
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
0

Share this post


Link to post
Share on other sites
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
0

Share this post


Link to post
Share on other sites
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
0

Share this post


Link to post
Share on other sites
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.
0

Share this post


Link to post
Share on other sites