Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 24 of 24

Thread: Object or Class?

  1. #1
    Junior Member mortalc's Avatar
    Join Date
    May 2010
    Posts
    15
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Object or Class?

    I'm designing a game not unlike LF2.
    What I'm wondering is - Should I use classes or objects for the characters? Basically the fields would be basic stats, Methods would be attack, die (if Health -> 0), take damage, etc. I'm not sure if Objects are complicated enough.
    (o o)
    {''''''}
    He has come for you.
    There is no escaoe.


  2. #2
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Object or Class?

    You'll want to use an object, but objects are defined via classes because you will want some specific traits for each character, but the type of traits will be the same.

    Ex:

    In a rectangle class, you would probably want a length/height characteristics, but the actual values will vary between each rectangle object. However, if you decide that you want your rectangles to only be so large, then this would be a class attribute since no rectangle should be larger than the maximum size.

    A more appropriate way to phrase the question would be static or instantiated. See: Lesson: Classes and Objects (The Java Language Tutorials)

  3. The Following User Says Thank You to helloworld922 For This Useful Post:

    mortalc (May 19th, 2010)

  4. #3
    Member
    Join Date
    Apr 2010
    Location
    The Hague, Netherlands
    Posts
    91
    Thanks
    3
    Thanked 10 Times in 10 Posts

    Default Re: Object or Class?

    Classes are the blueprints for objects.

  5. #4
    Member
    Join Date
    May 2010
    Posts
    36
    Thanks
    0
    Thanked 13 Times in 12 Posts

    Default Re: Object or Class?

    Quote Originally Posted by mortalc View Post
    Should I use classes or objects for the characters?
    there are no objects without classes and classes without objects doesn't make much sense. so the answer is: you need both.

  6. #5
    Super Moderator Json's Avatar
    Join Date
    Jul 2009
    Location
    Warrington, United Kingdom
    Posts
    1,274
    My Mood
    Happy
    Thanks
    70
    Thanked 156 Times in 152 Posts

    Default Re: Object or Class?

    Quote Originally Posted by j2me64 View Post
    there are no objects without classes and classes without objects doesn't make much sense. so the answer is: you need both.
    Just to play the devils advocate, classes without objects could be utility classes with only static methods and a private constructor

    // Json

  7. #6
    Member
    Join Date
    Apr 2010
    Location
    The Hague, Netherlands
    Posts
    91
    Thanks
    3
    Thanked 10 Times in 10 Posts

    Default Re: Object or Class?

    Quote Originally Posted by Json View Post
    Just to play the devils advocate, classes without objects could be utility classes with only static methods and a private constructor

    // Json
    As a note to add: if someone wants to go deeper into it, google the Singleton pattern and you'll understand

  8. #7
    Junior Member mortalc's Avatar
    Join Date
    May 2010
    Posts
    15
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Object or Class?

    Right. Thanks!.
    (o o)
    {''''''}
    He has come for you.
    There is no escaoe.

  9. #8
    Junior Member mortalc's Avatar
    Join Date
    May 2010
    Posts
    15
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Object or Class?

    I can't figure out how to create an object (without simply using new; I mean creating one as you would a class).
    Basically, The Character will be refrenced continuously throughtout the code. Can I simply say "Object extends Class"?
    Also, There will be several characters, and each with the same fields (health, strength, etc.).
    Say the method "attack" would decrease the attacked's health by the attacker's strength. Which of the two characters would have the method - the attacked or the attacker? And how would I put a field of a different character in a method of another, when it will have a variable of the same name?
    (o o)
    {''''''}
    He has come for you.
    There is no escaoe.

  10. #9
    Forum old-timer
    Join Date
    Nov 2008
    Location
    Faversham, Kent, UK
    Posts
    472
    My Mood
    Mellow
    Thanks
    4
    Thanked 58 Times in 54 Posts

    Default Re: Object or Class?

    Did you read the tutorial at the link provided?

  11. #10
    Forum old-timer
    Join Date
    Nov 2008
    Location
    Faversham, Kent, UK
    Posts
    472
    My Mood
    Mellow
    Thanks
    4
    Thanked 58 Times in 54 Posts

    Default Re: Object or Class?

    Quote Originally Posted by Bryan View Post
    As a note to add: if someone wants to go deeper into it, google the Singleton pattern and you'll understand
    A singleton isn't the same as a static-only class. A singleton (as its name suggests) is a single instance class - i.e. one that has a single object.

    Best Practice these days seems to frown on singletons because they can cause trouble and encourage poor design - YMMV.

  12. #11
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Object or Class?

    Technically, the JVM does have to instantiate a static instance of the class. However, the methods/fields of that static instance are different from the "normal" object fields (i.e. only contains the static fields/methods)

    In Java, all objects must extend Object (they extend this class by default so you don't really need to do anything)

    To define a class/object:
    public class MyObject
    {
         // class/object definition goes in here
    }

    To create a new object:

    MyObject someName = new MyObject();

    That link I provided should get you started with object-oriented programming in Java

  13. #12
    Member Faz's Avatar
    Join Date
    Mar 2010
    Posts
    97
    Thanks
    5
    Thanked 14 Times in 14 Posts

    Default Re: Object or Class?

    No offence but I think you should take on a few smaller easier projects before you try something too complex, just to get an understanding of Objects and Classes and all that lark.

  14. #13
    Super Moderator Json's Avatar
    Join Date
    Jul 2009
    Location
    Warrington, United Kingdom
    Posts
    1,274
    My Mood
    Happy
    Thanks
    70
    Thanked 156 Times in 152 Posts

    Default Re: Object or Class?

    Yes, dependency injection is a lot better.

    However to go back on track with this thread, what I guess you need to do is create a class that represents a character.

    // Dont mix this up with the Character wrapper class.
    public class Character {
     
        private int health;
     
        private int strength;
     
        public Character() {
     
        }
     
        public int getHealth() {
            return this.health;
        }
     
        public void setHealth(final int health) {
            this.health = health;
        }
     
        public int getStrength() {
            return this.strength;
        }
     
        public void setStrength(final int strength) {
            this.strength = strength;
        }
    }

    Then somewhere in your code, maybe when you initialise the game code, create objects etc.

    public void initialise() {
        final Character someCharacter = new Character();    
        final Character someOtherCharacter = new Character();    
     
       // Now store these somewhere
    }

    I'm not familiar with your framework but I take it you'd like to store the character somewhere so that you can grab it from your code whenever you want, you might have a GameState singleton or something like this to keep track of the current state including all characters and their stats as well as the objects and character inventories bla bla bla.

    For instance, in my game which is an arcade style game I have different scenes, one scene is the menu another is the actual playing and there are other things like high score scene etc. as well.

    When I'm in the menu of my game and I choose to start a new game, I initialise the PlayingScene which in turn creates and holds the current player object.

    playingScene.newGame();

    public void newGame() {
        // Reset the whole scene to the state of a new game, including the score, player, enemies etc.
        this.player = new Player(this.particleTexture);
    }

    The player then has a number of lives and some other basic stats on it as well as all the code for rendering the player, this might not be optimal but its the way I did it back in the days. Seeing as the player is just a small spaceship built up using two triangles I'm alright I think. Its a simple game anyway.

    Some sample rendering code.
                gl.glBegin(GL.GL_TRIANGLES);
                {
                    // Base
                    gl.glColor4f(0.2f, 0.5f, 0.2f, 1.0f);
                    gl.glVertex3f(-0.5f, 0.25f, 0.0f);
                    gl.glVertex3f(-0.5f, -0.25f, 0.0f);
                    gl.glColor4f(0.2f, 0.7f, 0.2f, 1.0f);
                    gl.glVertex3f(0.5f, 0.0f, 0.0f);
     
                    // Fin
                    gl.glColor4f(0.2f, 0.7f, 0.2f, 1.0f);
                    gl.glVertex3f(-0.5f, 0.0f, 0.0f);
                    gl.glVertex3f(0.5f, 0.0f, 0.0f);
                    gl.glColor4f(0.2f, 0.5f, 0.2f, 1.0f);
                    gl.glVertex3f(-0.5f, 0.0f, 0.5f);
                }
                gl.glEnd();

    Sorry for the long post, just give us a shout if you need any more help.

    // Json

  15. The Following User Says Thank You to Json For This Useful Post:

    mortalc (May 20th, 2010)

  16. #14
    Junior Member mortalc's Avatar
    Join Date
    May 2010
    Posts
    15
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Object or Class?

    Yes I did read the tutorial.
    It just doesn't seem to touch on what I want... Maybe what I want isn't possible in Java.
    Oh well.
    By the way, for the methods question, I had an idea. Basically, both the attacker and the attacked would have a method - the attacker initiates the attack, sending variables over with different names (e.g. s instead of strength) to the attacked, where the damage calculation would occur. Would it work?

    Ed:
    Sorry Json, I didn't see your post (I was looking at the first page!)! Thanks, I can see that will be a great help. My characters will probably just be stick men.
    @ Faz: I think you're right. Maybe something less ambitious... But that's the touble with me. I'm always too ambitious!
    Last edited by mortalc; May 20th, 2010 at 04:45 AM. Reason: Didn't see Json's post.
    (o o)
    {''''''}
    He has come for you.
    There is no escaoe.

  17. #15
    Member
    Join Date
    Apr 2010
    Location
    The Hague, Netherlands
    Posts
    91
    Thanks
    3
    Thanked 10 Times in 10 Posts

    Default Re: Object or Class?

    The calculation of the damage should not occur in the charater itself but some kind of damagehandler, or fighthandler or whatever. It ask the charaters its strength, do some math(fight) and if there is damage, reduce the health(s).

    Ofcourse this is possible in Java, you just have to know how. But like Faz already said, instead of building something this complex right at the beginning is not smart. Do some smaller projects so you get used to the language and then build the game. But first design the game itself because you want to program the game without having giving it a real thought, like we see now:
    By the way, for the methods question, I had an idea. Basically, both the attacker and the attacked would have a method - the attacker initiates the attack, sending variables over with different names (e.g. s instead of strength) to the attacked, where the damage calculation would occur. Would it work?
    A OO design should not be language dependant(else its not a OO design, imho). Sure, while programming it will become a bit more Java dependant but the design itself should not.

    Quote Originally Posted by dlorde View Post
    A singleton isn't the same as a static-only class. A singleton (as its name suggests) is a single instance class - i.e. one that has a single object.

    Best Practice these days seems to frown on singletons because they can cause trouble and encourage poor design - YMMV.
    I know, but I understood static-only classes better when I had read about the Singleton pattern. And also I dont think much about it, but as long as its used correctly and for the right things, I dont see the harm in it.

  18. #16
    Super Moderator Json's Avatar
    Join Date
    Jul 2009
    Location
    Warrington, United Kingdom
    Posts
    1,274
    My Mood
    Happy
    Thanks
    70
    Thanked 156 Times in 152 Posts

    Default Re: Object or Class?

    Yeah, so basically you would have this "FightHandler" or something and then just pass the two characters to it.

    new FightHandler().attack(characterA).with(characterB);



    // Json

  19. #17
    Member
    Join Date
    Apr 2010
    Location
    The Hague, Netherlands
    Posts
    91
    Thanks
    3
    Thanked 10 Times in 10 Posts

    Default Re: Object or Class?

    Quote Originally Posted by Json View Post
    Yeah, so basically you would have this "FightHandler" or something and then just pass the two characters to it.

    new FightHandler().attack(characterA).with(characterB);



    // Json
    Exactly, and this way you can hold different kind of fights You could make FightHandler abstract and make something like GunFightHandler or MultipleFightHandler(go crazy on it!!). But if you dont have a good design of the entire game, you'll be programming for a longg... time.

  20. #18
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Object or Class?

    Games are very easily maintained using events, however writing custom events in Java is very cumbersome. You have to create the event class, an interface that objects must implement in order to recieve the events, and then in each class that can send out that event, add methods to add/remove objects from the "send event to" list. Of course, you can get around having to write the interface if you extend a pre-made event, or have all your events inherit from a main class of events you create, but the time-consuming portion is having your class send out the event/maintain a list of event listeners (that being said, it's not too bad at all).

    FYI, to simplify keeping track of the event listeners, you can extend AWTEvent and use an event listener list (I forgot the precise name, a quick google should turn up with the correct result) and simply add/remove this way.

    So, say you had an attack event:
    public class AttackEvent extends ActionEvent
    {
         private double damage;
         public AttackEvent(Object source, double damage)
         {
              super(source, 0, "attack");
              this.damage = damage;
         }
     
         public double getRawDamage
         {
              return damage;
         }
    }

    With this type of a system, you can handle different kinds of attacks easily and follow a better OO model since the amount of raw damage done is being sent from the attacker and recieved by the defender, which can then decide how much damage should be reduced for armor/shields, or how much extra damage should be done in the case of a "critical hit", or even if the attack misses and no damage is done (like trying to attack a flying enemy with a sword)

  21. #19
    Junior Member mortalc's Avatar
    Join Date
    May 2010
    Posts
    15
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Object or Class?

    Hokay, heregoes. This is what I've got so far - Just the Character class and a Character. Tell me if I've made any mistakes:

    public class Character {
        private int health=50;
        private int strength;
    	private int defense;
    	private int attackSpeed;
    	private int speed;
     
        public Character() {
        }
     
        public int getHealth() {
            return this.health;
        }
     
        public void setHealth(final int health) {
            this.health = health;
        }
     
        public int getStrength() {
            return this.strength;
        }
     
        public void setStrength(final int strength) {
            this.strength = strength;
        }
        public int getDefense() {
            return this.defense;
        }
     
        public void setDefense(final int defense) {
            this.defense = defense;
        }
        public int getAttackSpeed() {
            return this.attackSpeed;
        }
     
        public void setAttackSpeed(final int attackspeed) {
            this.attackSpeed = attackSpeed;
        }
        public int getSpeed() {
            return this.speed;
        }
     
        public void setSpeed(final int speed) {
            this.speed = speed;
        }
    }
     
    Character Harland = new Character(); 
    {
    final int strength = 10
    final int defense = 9
    final int attackSpeed = 3
    final int speed = 6
    }
    (o o)
    {''''''}
    He has come for you.
    There is no escaoe.

  22. #20
    Member Darryl.Burke's Avatar
    Join Date
    Mar 2010
    Location
    Madgaon, Goa, India
    Posts
    494
    Thanks
    8
    Thanked 48 Times in 46 Posts

    Default Re: Object or Class?

    zumali's post reported for link spamming

    db

  23. The Following 2 Users Say Thank You to Darryl.Burke For This Useful Post:

    javapenguin (June 21st, 2012), Json (May 21st, 2010)

  24. #21
    Junior Member mortalc's Avatar
    Join Date
    May 2010
    Posts
    15
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Object or Class?

    Is my code right?

    Also, does the tutorial cover everything? Just there are some things that you've mentioned that I don't understand, and much of it You'll have to forgive me this - I like to understand how everything works. a bit of a flaw, really.
    If it is in the tutorial, and I'm just being a idiot, Could you please give me the link?

    Quote Originally Posted by Json View Post
    public void initialise() {
        final Character someCharacter = new Character();    
        final Character someOtherCharacter = new Character();
    What does the 'initialise' do? Alright, silly question. But what does that block of code as a whole do?

    Quote Originally Posted by Json View Post
    playingScene.newGame();
    How does this work?

    Quote Originally Posted by Json View Post
    public void newGame() {
        // Reset the whole scene to the state of a new game, including the score, player, enemies etc.
        this.player = new Player(this.particleTexture);
    }
    Same here. Especially the last bit.

    Quote Originally Posted by Json View Post
    new FightHandler().attack(characterA).with(characterB);
    This could be helpfull - is it an 'object'? Or something else entirely? And HDIW?
    Quote Originally Posted by helloworld922 View Post
    Games are very easily maintained using events, however writing custom events in Java is very cumbersome. You have to create the event class, an interface that objects must implement in order to recieve the events, and then in each class that can send out that event, add methods to add/remove objects from the "send event to" list. Of course, you can get around having to write the interface if you extend a pre-made event, or have all your events inherit from a main class of events you create, but the time-consuming portion is having your class send out the event/maintain a list of event listeners (that being said, it's not too bad at all).
    Is there any difference between an event class and a normal class? Or am I being an idiot again?


    Quote Originally Posted by helloworld922 View Post
    public class AttackEvent extends ActionEvent
    {
         private double damage;
         public AttackEvent(Object source, double damage)
         {
              super(source, 0, "attack");
              this.damage = damage;
         }
     
         public double getRawDamage
         {
              return damage;
         }
    }
    What does the 'double' do? I found it on the tutorial, in the maths section, being used with operators such as 'cos' and 'exp'. But what does it do on its own?
    What about 'source' and 'get___'?

    Quote Originally Posted by helloworld922 View Post
    With this type of a system, you can handle different kinds of attacks easily and follow a better OO model since the amount of raw damage done is being sent from the attacker and recieved by the defender, which can then decide how much damage should be reduced for armor/shields, or how much extra damage should be done in the case of a "critical hit", or even if the attack misses and no damage is done (like trying to attack a flying enemy with a sword)
    How would I do this?


    Sorry about this. Thanks in advance?
    (o o)
    {''''''}
    He has come for you.
    There is no escaoe.

  25. #22
    Super Moderator Json's Avatar
    Join Date
    Jul 2009
    Location
    Warrington, United Kingdom
    Posts
    1,274
    My Mood
    Happy
    Thanks
    70
    Thanked 156 Times in 152 Posts

    Default Re: Object or Class?

    Not to sound too much like everyone else now but some of these questions are really making me wonder if you shouldn't try some basic tutorials first or at least make some minor things on the way to your complete game.

    For instance, a double is the biggest floating point value representation in Java. I usually refer people to have a read at The Really Big Index and in this case this page is even more of a help Primitive Data Types (The Java™ Tutorials > Learning the Java Language > Language Basics)

    With the initialise method what I had in mind was that when you load your game you will most likely have to initialise a lot of things, load textures, sounds etc. An initialise method is the way to go.

    public class MyGame {
     
        public static void main(final String... arguments) {
            final MyGame myGame = new MyGame();
            myGame.initialise();
     
        }
     
        public void initialise() {
            // Load sounds
            // Load textures
            // Load other resources
            // Create your characters
            // etc...
        }
     
    }

    A simple example above.


    When it comes to events, event classes are just normal classes, thats true but what happens with events is that you usually have an eventmanager of some kind and then an interface defining what an EventListener is and as your game goes on and something happens, like for instance character a being attacked by character b you can tell your eventmanager to trigger an event called AttackEvent. The event manager would then send this event out to any event listeners it has registered and then the listeners can do whatever they want with the event. In the actual event class that gets sent out you could pass in the character being attacked and the one defending for example. Like helloworld said, check out AWT or something or have a look at Lesson: Writing Event Listeners (The Java™ Tutorials > Creating a GUI With JFC/Swing)

    You also asked if the FightHandler example above is an object, in a sense, in Java everything is more or less an object, here's a small example.

    Fight class
    public class Fight {
     
        private Character defender;
     
        private Character attacker;
     
        public void with(final Character character) {
            this.attacker = character;
            this.calculate();
        }
     
        public Fight attack(final Character character) {
            this.defender = character;
            return this;
        }
     
        private void calculate() {
            this.defender.decreaseHealth(10);
            this.attacker.increaseExperience(100);
     
            System.out.println("[" + this.attacker.getName() + "] attacks [" + this.defender.getName() + "] causing [10] damage and gains [100] experience");
        }
    }

    Character class
    public class Character {
     
        private final String name;
     
        private int health = 100;
     
        private int experience = 0;
     
        public Character(final String name) {
            this.name = name;
        }
     
        public void decreaseHealth(final int amount) {
            this.health -= amount;
        }
     
        public void increaseExperience(final int amount) {
            this.experience += amount;
        }
     
        public int getHealth() {
            return this.health;
        }
     
        public void setHealth(final int health) {
            this.health = health;
        }
     
        public int getExperience() {
            return this.experience;
        }
     
        public void setExperience(int experience) {
            this.experience = experience;
        }
     
        public String getName() {
            return this.name;
        }
    }

    Game class
    public class MyGame {
        public static void main(final String[] args) {
            final Character characterA = new Character("Character A");
            final Character characterB = new Character("Character B");
     
            new Fight().attack(characterA).with(characterB);
        }
    }

    // Json

  26. #23
    Junior Member mortalc's Avatar
    Join Date
    May 2010
    Posts
    15
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Object or Class?

    Thankyou.
    I think I will start with something less ambitious - ideas?
    I will certainly refer to here when I do get started on my game.

    Ed:
    I've had an idea. Basically, it takes place on a 50x50 board (Squares are invisible). Every X seconds, a 'bomb' appears on a random square, lasting Y seconds. This would continue until Z% of the squares are filled with bombs - after that, each time a 'bomb' dissapears, another one appears somewhere else. The game ends when the mouse pointer either touches a 'bomb' or moves off the board. Then, an alert appears saying how long they lasted.
    Things I'm not sure how to do are:
    1. Making the bombs (an object, ofc) actually visible (possible as a mine like in minseweeper).
    2. Making them appear at random squares
    3. Making the grid
    4. Making sure that a bomb will not appear on the same square as one already present
    5. Making the game terminate when a bomb is moused over
    6. Timing how long it takes
    7. The pop up.

    5 through 7 I can do in Javascript, but that's probably irrelevant. 1 and 3 would help me in my future game.
    Also, as for the tutorial, I find that I can get into books much more easily than web pages, so I'll probably buy/borrow a book on Java. One that's engaging and includes EVERYTHING.
    Last edited by mortalc; May 22nd, 2010 at 11:28 AM. Reason: I've had an idea!
    (o o)
    {''''''}
    He has come for you.
    There is no escaoe.

  27. #24
    Junior Member
    Join Date
    Aug 2010
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Object or Class?

    The objects are loaded into memory before processing. The newly created object must be a newly allocated memory to hold instance variables of the object, this is done by the Java Virtual Machine (JVM). Initialization of the object is very important in programming, because it is a frequent source of error. The Java programming language provides various mechanisms included to ensure proper initialization of the memory occupied by a newly created object that helping things to get a valid state initial.

Similar Threads

  1. 2D Object makes my object smaller, Why?
    By MassiveResponse in forum What's Wrong With My Code?
    Replies: 2
    Last Post: May 15th, 2010, 02:33 PM
  2. How to create a new object of another class within a method
    By davie in forum Object Oriented Programming
    Replies: 1
    Last Post: April 16th, 2010, 05:53 PM
  3. Class and Object
    By jyothishey in forum Object Oriented Programming
    Replies: 2
    Last Post: January 25th, 2010, 08:48 AM
  4. Replies: 2
    Last Post: November 5th, 2009, 10:15 PM
  5. Having trouble printing object information in main class
    By KingLane in forum Object Oriented Programming
    Replies: 1
    Last Post: October 11th, 2009, 06:53 PM