Enums and Interfaces ??

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 :frowning:

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 :confused:

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

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.

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

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:

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:

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.

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. :slight_smile:

Thanks, i think i understand the Enums now :slight_smile:

and yes i will be programming it :slight_smile: 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 :slight_smile:

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.

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(). 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):


    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.

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

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 :slight_smile:

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.

i will look into this one :slight_smile:

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.

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.

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 :stuck_out_tongue:


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;
	}
}

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

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.

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 :smiley:

so… tell me i got this crosses fingers

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();
}

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.

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

Thanks :slight_smile: i think i’m starting to understand… only 2 hours until i’m home and can start playing :slight_smile: … not to check out what Abstract is (thanks davedes hehe)

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.

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.

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: