Java-Gaming.org    
Featured games (81)
games approved by the League of Dukes
Games in Showcase (487)
Games in Android Showcase (112)
games submitted by our members
Games in WIP (553)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  Enums and Interfaces ??  (Read 2100 times)
0 Members and 1 Guest are viewing this topic.
Offline andyMak

Senior Newbie





« Posted 2012-06-29 00:40:27 »

Hi guys,

so i have been reading and following tutorials, i understand

  • Methods
  • Constructors
  • Instantiation
  • Encapsulation
  • Polymorphism
  • The basics (flow control, loops, etc)
  • event Handlers
  • +more

The problem i'm having is Interfaces and Enums Sad

Enums: I'm having trouble understanding why we would use them, what they are for, what they do

Interfaces: i understand that they work as a contract such as a class that inherits them must include / implement the methods defined within them but still not sure why we would use them as one class that inherits the methods may write them completely different that another class :/

I'm wondering if anyone knows of a nice site / tutorial (written) that could explain these for me clearly and examples of simple use that would be clear to a complete dolt like myself.


cheers

There are 3 types of people in this world, those who can count and those who can't!
Offline UprightPath
« Reply #1 - Posted 2012-06-29 00:59:13 »

Enums: You have a static set of values/objects that represent something, which might have other data beyond just being 'constant'. In my case, I use them to represent things like Non-binary directional data, or in my Platformer game, I use them to define the Tile Information and be able to access them to from a semi-static position (They have the height mask, angle, other data/methods).

Interfaces: Simply put "Java does not have multiple inheritance". Not the exact reason, but a good enough one. Let's say you're writing on a game and you need certain objects, that don't have a common 'parent' to be treated the same way for the purposes of certain operations. Example- Tiles VS Entities. Tiles are statically placed and are not affected by gravity/forces while Entities can be moved/affected by other entities, react to collisions, etc. While in my game they could, possibly, extend the same super class it was easier for me (Since I'd have to add an extra layer of inheritance) to just provide a Positioned interface, which keeps track of it's map position and provides some stuff for collision detection.

Perhaps a bad example, but... Yeah.

Offline andyMak

Senior Newbie





« Reply #2 - Posted 2012-06-29 01:11:52 »

Thanks, good examples i think but they still confuse me, maybe the'll make more sense when i actually need to use them.

I hate moving on without fully understanding something, i feel if i just let it go and wait till i need them and carry on learning i might not understand something down the track

There are 3 types of people in this world, those who can count and those who can't!
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline davedes
« Reply #3 - Posted 2012-06-29 01:23:24 »

If you understand polymorphism you should see the benefit in Interfaces. A good example is in Java's Collections API:
http://docs.oracle.com/javase/6/docs/api/java/lang/Iterable.html

iterator() is a common method in many data types -- lists, arrays, hash maps, etc. HashMaps do implement the method completely differently from array lists, but the end result (an iterator) is the same. Presumably whoever is writing the classes has sense enough to do what the interface method expects.

Another simple example might be serializing entities/sprites/etc for your JSON-based game:
1  
2  
3  
4  
public interface JSONSerializable {
    public void store(OutputStream out) throws IOException;
    public void load(InputStream in) throws IOException;
}


Enums are used for constant values, much handier than using a constant int/String/etc. Little example:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
public enum Shape {
    TRIANGLE(3),
    RECTANGLE(4),
    PENTAGON(5);

    private int sides;

    public Shape(int sides) {
        this.sides = sides;
    }

    public int getSideCount() {
        return sides;
    }
}


It's nicely checked at compile time, which means you won't mix up the Shape enum with any other enum constants your game has created.
1  
2  
3  
4  
5  
Shape s = Shape.RECT;
System.out.println(s.getSideCount()); => 4
System.out.println(s.toString()); => "RECT"
System.out.println(Shape.values()[0]); => TRIANGLE
System.out.println(Shape.valueOf("TRIANGLE").getSideCount()); => 3


Really the best way to learn isn't by reading tutorials, but by actually programming. Smiley

Offline andyMak

Senior Newbie





« Reply #4 - Posted 2012-06-29 01:41:47 »

Thanks, i think i understand the Enums now Smiley

and yes i will be programming it Smiley but whilst im at work i have tutorials opened in the background i read whilst working.

at uni i've had to make a program that accept command line args as well as running without using the command line. depending on the args it would initiate a different part of the program (i think there was a compound interest one, a table of employee names that could be edited and a library, could see what books were out could rent / borrow books)

it's been about a year since i completed the java unit and haven't really touched it since.. 2 semesters away i have programming 2 which focuses more on java. in the mean time i was hoping to freshen up on the basics and try to create pong, once i have pong working then try the Breakout game then maybe a tetris and then eventually a platformer of something Smiley

i don't struggle as much when i use Actionscript 3 but compared to Java i don't like the syntax of somethings, i'm really liking java right now.

There are 3 types of people in this world, those who can count and those who can't!
Offline philfrei
« Reply #5 - Posted 2012-06-29 02:32:33 »

When I first came across Interfaces, I had some trouble with them too. I thought "Head First Java" did a reasonably good job of explaining them.

Example of a use for Interfaces:

In my game I have all sorts of objects that are animated. Instead of making them all have a common parent class, I made an Interface called Animateable, and gave it a method "updateAnimation". All objects that get updated once per frame implement this Interface.

Then, in my game loop, I have a collection of all the objects, as a new ArrayList<Animateable>(). All objects which implement Animateable can be placed in this array.

In the game loop is a for:each block, that iterates through this collection and calls each object's "updateAnimation" method, once per frame, and then does the repaint() call.

So, inside the game loop can be something as compact and clean as this (plus a little something to handle keeping the timing consistent):
1  
2  
3  
4  
5  
    for (Animateable a : animationObjects)
    {
         a.updateAnimation();
    }
    displayScreen.repaint()

Even though the objects are very diverse, and don't share anything except the need to update once per game loop, they can all be handled in a single code block with just a couple lines. There's no need for any casting, or any statements to determine the type of object. Also, each object can implement its update in its own way--the code to do so can reside within the object.

"Greetings my friends! We are all interested in the future, for that is where you and I are going to spend the rest of our lives!" -- The Amazing Criswell
Offline sproingie

JGO Kernel


Medals: 202



« Reply #6 - Posted 2012-06-29 02:36:10 »

Even with its cheesy hip "attitude", Head First Java is a really really good book for learning Java.
Offline andyMak

Senior Newbie





« Reply #7 - Posted 2012-06-29 02:39:28 »

so could you not just make an animateable class with this update .....

hang on just as i was typing this.. i thought havinge an Animatable class would be fine IF you could extend more than once.. i think i get it.. the objects all have difference parents so they cant extend this aswell so instead.. make an interface Smiley

But then the question, the code is not created in the interace so is the updateAnimation method written in each class? so a player enemy items and all that each have updateAnimation method within the class? that's the part that confuses me as why have an interface that doesn't actually have the code in the methods because the code is being placed in each class anyway making the interface redundant?

i hope that makes sense.

There are 3 types of people in this world, those who can count and those who can't!
Offline andyMak

Senior Newbie





« Reply #8 - Posted 2012-06-29 02:39:52 »

Even with its cheesy hip "attitude", Head First Java is a really really good book for learning Java.


i will look into this one Smiley

There are 3 types of people in this world, those who can count and those who can't!
Offline davedes
« Reply #9 - Posted 2012-06-29 02:48:57 »

so could you not just make an animateable class with this update .....

hang on just as i was typing this.. i thought havinge an Animatable class would be fine IF you could extend more than once.. i think i get it.. the objects all have difference parents so they cant extend this aswell so instead.. make an interface Smiley

But then the question, the code is not created in the interace so is the updateAnimation method written in each class? so a player enemy items and all that each have updateAnimation method within the class? that's the part that confuses me as why have an interface that doesn't actually have the code in the methods because the code is being placed in each class anyway making the interface redundant?

i hope that makes sense.
Generally you would design your objects to minimize or completely eliminate duplicate code.

For example, we have the following interfaces:
Animatable - with updateAnimation()
Renderable - with draw()

Then you may have Sprite, which implements the two interfaces and provides functionality to those methods. To reduce repetition, you would make both Player and Enemy (and whatever else you may need, like Bullet or Ship) extend Sprite.

Then you may still have other types that implement Animatable, but you don't want to extend Sprite since they rely on a totally different functionality. For example, a timer or clock which needs to be updated, yet it doesn't need to be rendered. In that case, we can implement Animatable, but we don't need to implement Renderable.

Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline philfrei
« Reply #10 - Posted 2012-06-29 02:50:35 »

I think you are getting it.

Yes, the Interface CAN have common code or variables that are shared, lessening redundancy.

But also, sometimes objects are very different. For example, one object may never change location, but rather only changes color or shape (or some other aspect of state) somehow, whereas another moves around, etc.

Or an object may EITHER move or explode in place--those are two very different types of animation needs. The game loop shouldn't have to care which is happening.

So, you might not want xLoc & yLoc & xVel & yVel etc. or some other parts of the animation code to be shared, if they are not being used by some of the objects.

"Greetings my friends! We are all interested in the future, for that is where you and I are going to spend the rest of our lives!" -- The Amazing Criswell
Offline andyMak

Senior Newbie





« Reply #11 - Posted 2012-06-29 02:58:51 »

see if this shows what's going on through my head.. i read that you only declare in an interface (as per code below)

so in my head i'm seeing the same thing being written in each class (repeated) which really to me makes the interface useless

*hopefully this shows you what my head is doing, maybe i'm understanding them all wrong Tongue

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
interface Animate (){

   void updatePosition();
}

public class Player implements Animate(){

   public void updatePosition(){
      this.x += 5;
      this.y += 5;
   }
}

public class Enemy implements Animate(){

   public void updatePosition(){
      this.x += 5;
      this.y += 5;
   }
}

public class AnotherObject implements Animate(){

   public void updatePosition(){
      this.x += 5;
      this.y += 5;
   }
}

There are 3 types of people in this world, those who can count and those who can't!
Offline davedes
« Reply #12 - Posted 2012-06-29 03:06:58 »

In your case, you are not benefitting by using interfaces. Just use simple inheritance.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
class Sprite {
   ...

   public void updatePosition(){
      this.x += 5;
      this.y += 5;
   }
}

class Enemy extends Sprite {
    ...
}

class Ship extends Sprite {
    ...
}


Alternatively, you could use abstract classes to maintain the "flexibility" of an interface while still minimizing duplicate/common code.
1  
2  
3  
4  
5  
6  
interface Sprite; <-- the absolute bare-bones sprite
abstract class AbstractSprite implements Sprite; <-- implements basic functionality to reduce code duplication
class Player extends AbstractSprite;
class Enemy extends AbstractSprite;
class Boss extends Enemy;
etc.


Though I would opt for the first (just simple inheritance) for the sake of simplicity, and then refactor later if you find it absolutely necessary.


EDIT: Sorry if introducing abstract just made the whole thing more confusing... haha Cheesy

Offline andyMak

Senior Newbie





« Reply #13 - Posted 2012-06-29 03:35:19 »

so.. tell me i got this *crosses fingers*


1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
interface Animate (){

   void updatePosition();
}

public class Sprite extends Something implements Animate(){

   public void updatePosition(){
    this.x += 5;
      this.y += 5;
   }
}

public class Enemy extends Sprite(){

   updatePosition()
}

public class Boss extends Enemy(){

   updatePosition()
}

public class AnotherObject extends Sprite(){

   updatePosition();
}
 

There are 3 types of people in this world, those who can count and those who can't!
Offline ra4king

JGO Kernel


Medals: 345
Projects: 2
Exp: 5 years


I'm the King!


« Reply #14 - Posted 2012-06-29 05:21:48 »

Quick point, when extending or implement, you don't include parenthesis next to the name Wink

Interfaces are handy for, as the others said, providing one overall "blueprint" for what each class that implements it should have.

This makes them useful for many things, but the most useful, as you saw philfrei showed, is to be able to "group" them together and or reassign them.

Many different completely unrelated classes could be grouped together through an Interface, for example "Animatable", into an ArrayList or other collections.

You could also have an Animatable variable that you can simply reassign, like let's say a GUI Button that shows different animations depending on what is selected. The "Button" class can have an "Animatable animation;" global variable that it just assigns different instances of unrelated classes that all agree to the contract of Animatable.

Offline andyMak

Senior Newbie





« Reply #15 - Posted 2012-06-29 05:32:58 »

Quick point, when extending or implement, you don't include parenthesis next to the name Wink

I knew this i was just checking if you guys would pick up on it Tongue

Interfaces are handy for, as the others said, providing one overall "blueprint" for what each class that implements it should have.

This makes them useful for many things, but the most useful, as you saw philfrei showed, is to be able to "group" them together and or reassign them.

Many different completely unrelated classes could be grouped together through an Interface, for example "Animatable", into an ArrayList or other collections.

You could also have an Animatable variable that you can simply reassign, like let's say a GUI Button that shows different animations depending on what is selected. The "Button" class can have an "Animatable animation;" global variable that it just assigns different instances of unrelated classes that all agree to the contract of Animatable.

Thanks Smiley i think i'm starting to understand... only 2 hours until i'm home and can start playing Smiley ... not to check out what Abstract is  (thanks davedes hehe)

There are 3 types of people in this world, those who can count and those who can't!
Offline ra4king

JGO Kernel


Medals: 345
Projects: 2
Exp: 5 years


I'm the King!


« Reply #16 - Posted 2012-06-29 05:36:18 »

An abstract class is the marriage of interfaces and normal classes. It lets you specify abstract methods, which are just like interfaces where they have no body, and normal methods that have bodies. You cannot create instances of abstract classes. Just like interfaces, they are meant to be inherited. Any class that extends an abstract class must implement all abstract methods.

Offline andyMak

Senior Newbie





« Reply #17 - Posted 2012-06-29 05:40:14 »

An abstract class is the marriage of interfaces and normal classes. It lets you specify abstract methods, which are just like interfaces where they have no body, and normal methods that have bodies. You cannot create instances of abstract classes. Just like interfaces, they are meant to be inherited. Any class that extends an abstract class must implement all abstract methods.

Interfaces
Class implements this it MUST implement all methods ?

Abstract class
Class implements this it MUST implement all ABSTRACT methods


Man Java is much harder than the other stuff i've learnt... (html CSS and AS2 .. learning AS3 now)


Quesiton:

I chose Java because of cross-platform, looked easier and i've done a bit of it.

should i have chosen something else to begin game programming? i don't want to touch c++ but maybe i should've gone with c# or Python or Maybe Java is perfect.

There are 3 types of people in this world, those who can count and those who can't!
Offline 65K
« Reply #18 - Posted 2012-06-29 06:29:06 »

should i have chosen something else to begin game programming? i don't want to touch c++ but maybe i should've gone with c# or Python or Maybe Java is perfect.
Languages, libraries and tools are exchangable. Much more important are the concepts behind.
Only definitely stay away from a 3-eyed mutant like C++.
Choosing Java will confront you with OOP. You dont have to use interfaces e.g., but is still important to understand the background when dealing with external libraries. Then you have freedom of thoughtful choice.
So I recommend getting a good book for an OOP introduction as well.

Offline ra4king

JGO Kernel


Medals: 345
Projects: 2
Exp: 5 years


I'm the King!


« Reply #19 - Posted 2012-06-29 06:50:28 »

If you think this is hard, Java is one of the easiest languages to learn. C++ is a billion times more complex.

All this stuff may sound overwhelming, but trust me, once you get to use them, they are easy as pie Wink

Offline sproingie

JGO Kernel


Medals: 202



« Reply #20 - Posted 2012-06-30 00:45:39 »

Python or Javascript might be a little easier for learning, since you no longer worry about type safety, you just let things crash at runtime if you use them wrong.  Turns out that's just fine for some kinds of software.

I used to be a real disciple of static typing, but now I see it as just another development tool to use where it's appropriate and discard where it's not.  Some of the most robust programs I've written are in Scala, which is an insanely strongly-typed language -- but the robustness comes from using Akka actors, which are basically untyped!

Dittos on C++'s complexity, or as I've heard it described: "C++ is an octopus made by nailing extra legs to a dog."


Offline ReBirth
« Reply #21 - Posted 2012-06-30 05:01:49 »

You just let things crash at runtime if you use them wrong.
Oh God.

Offline matheus23

JGO Kernel


Medals: 106
Projects: 3


You think about my Avatar right now!


« Reply #22 - Posted 2012-06-30 08:00:57 »

What I like about C++ are the Enums... I tried to use Java's enums one time... But it wasn't that, I wanted to have. I just wanted to have something like in C++, in Java Enums are classes. Why?!? Of course that has some advantages, but I don't "use" them. Simply having an enum to make tons of "public static final int"s would be everything I want. Everything else is overkill for me...

But andyMak, starting with C++ is much harder anyways.

Fun fact: I used to try out C++ one time. My project built fine, until I somewhere (i didn't know where) I wrote something my compiler didn't like. Changeing ONE thing made (exactly) 108 (!!!) Compiler errors come up. I took me days to figure out, what my compiler (gcc) didn't like -.-
Btw, did I already say that I hate headers? It's like: "Hey you! Please write your classes/files twice Wink thank you !"...

Believe me, just stay with Java. Java gives you the most nice Error handling thingie. You get NullPointerExceptions, which are - by far - better than writing C++ code and then figuring out something goes wrong because there is some Object missing. Everything does so strange things then. Also, Java does not allow you to try to access "uninitialized" memory. That means these bytes you have, have still got the value someone set it to, which is mostly some random value or 0. Made me cracy one time.

I think it is possible to get along with C++... But you have to have a lot of patience.

See my:
    My development Blog:     | Or look at my RPG | Or simply my coding
http://matheusdev.tumblr.comRuins of Revenge  |      On Github
Offline Orangy Tang

JGO Kernel


Medals: 56
Projects: 11


Monkey for a head


« Reply #23 - Posted 2012-06-30 10:53:04 »

Fun fact: I used to try out C++ one time. My project built fine, until I somewhere (i didn't know where) I wrote something my compiler didn't like. Changeing ONE thing made (exactly) 108 (!!!) Compiler errors come up. I took me days to figure out, what my compiler (gcc) didn't like -.-

When trying to fix C++ compile errors, *always* start at the first error reported, and recompile when you think you've fixed it. C++ compilers are incredibly bad at recovering from a syntax error - the classic one is leaving the trailing ; off the end of a class declaration which can easily trigger thousands of errors.

[ TriangularPixels.com - Play Growth Spurt, Rescue Squad and Snowman Village ] [ Rebirth - game resource library ]
Offline Roquen
« Reply #24 - Posted 2012-06-30 12:31:39 »

Actually that's awesome and by design.  Scripting languages should be as fault tolerate as possible...different design space.  If I ever get off my butt and work on that entity-system article....I'll suggest doing exactly the same.
Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

TehJavaDev (12 views)
2014-08-28 18:26:30

CopyableCougar4 (24 views)
2014-08-22 19:31:30

atombrot (37 views)
2014-08-19 09:29:53

Tekkerue (30 views)
2014-08-16 06:45:27

Tekkerue (29 views)
2014-08-16 06:22:17

Tekkerue (18 views)
2014-08-16 06:20:21

Tekkerue (27 views)
2014-08-16 06:12:11

Rayexar (65 views)
2014-08-11 02:49:23

BurntPizza (41 views)
2014-08-09 21:09:32

BurntPizza (33 views)
2014-08-08 02:01:56
List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50

List of Learning Resources
by SilverTiger
2014-07-31 16:26:06

List of Learning Resources
by SilverTiger
2014-07-31 11:54:12

HotSpot Options
by dleskov
2014-07-08 01:59:08
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!