Java-Gaming.org    
Featured games (91)
games approved by the League of Dukes
Games in Showcase (579)
games submitted by our members
Games in WIP (500)
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  
  Abstract classes and interfaces help  (Read 1090 times)
0 Members and 1 Guest are viewing this topic.
Offline JESTERRRRRR

Senior Member


Medals: 6
Exp: 1 year



« Posted 2011-12-18 19:47:10 »

I've been reading up on abstract classes and interfaces, and I'm really confused.

My usual practice is to make a class, e.g. 

class NPC

then

SpecificNPC extends NPC

This lets me create an array that holds NPC objects, and then stores the subclasses, so

NPC[] enemies = new NPC[10];
enemies[0] = new SpecificNPC(args)


Simple as that really, where the specific npc can override methods like attack to use different attacks, but keep movement the same. I understand an interfaces mean you have to override the methods they contain, and have no body, but how does this affect the way I have been using polymorphism ?(I think thats what i did in the enemies array?)

Also I still dont understand why you'd use a interface over abstract class, visa versa, or an abstract class over the way I have been doing it? Just wondering if anyone can help. The book I have teaches me about them, but gives me no idea of why I would ever use them.
Offline sproingie
« Reply #1 - Posted 2011-12-18 19:52:35 »

An interface acts like an abstract class except, as you said, you can't inherit an implementation, you have to provide it.  Interfaces also can't have fields, except for static ones.  The other distinguishing feature of interfaces is that you can implement more than one of them, whereas you can only extend one class.  

Other than that, you treat interfaces pretty much the same as classes.  You should usually prefer an interface over an abstract class, unless you have a partial implementation that's shared by all the common subclasses. Using interfaces, you can rearrange your class hierarchy around without having to change code that takes an interface as an argument.  If you use only inheritance on the other hand, changing what classes objects inherit from usually means having to change everything that works with those classes, even if they didn't use the parts that changed.

Offline philfrei
« Reply #2 - Posted 2011-12-19 00:24:27 »

sproingie's answer is a good one.

The issue also comes up with the advice to "prefer composition to inheritance."

Joshua Bloch's "Effective Java" gets into this stuff.

"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
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline Catharsis

Junior Member




EGR Software rocks!


« Reply #3 - Posted 2011-12-19 05:14:01 »

An interface essentially is a public contract. In Java it's also a top level type that is referenced by it's class. IE <interface name>.class

In your case with a base NPC class consider if there were private implementation details that could differ between a conceivable second base NPC class. This could be anything really. Creating an NPC interface ("INPC") that provides the public contract allows you to use either base NPC types interchangeably. An example of this is that say you create a collection ArrayList<INPC>. Now you can put either base types into this list and iterate over the common interface.

Interface based programming is important in larger architectures and app dev. In your case you may get away with things for a while depending on the scope of your efforts.

Interfaces are useful when private internal implementations differ, but the external public contract is the same between different implementations.

Founder & Principal Architect; EGR Software LLC
http://www.typhonrt.org/
http://www.egrsoftware.com/
Offline sproingie
« Reply #4 - Posted 2011-12-19 07:02:37 »

Agreed with all the above except for one nitpick: I really don't recommend this "prefixing Interfaces with IFoo IBar IBlah" business.  The point of an interface is not to be special and call attention to itself as an interface, but to act as any other class would, and having a naming convention only for interfaces defeats the purpose.  It works well for COM because interfaces in COM really are distinct from classes, but nowhere in the JDK do you find interfaces using this convention, and frankly it's a mistake for .NET to have done it that way.

Offline JESTERRRRRR

Senior Member


Medals: 6
Exp: 1 year



« Reply #5 - Posted 2011-12-19 07:22:38 »

Thanks guys that was alot clearer. Say all my classes are going to have an 'update', and a 'draw' method, regardless of what they are, that differ per subclass. These are the only methods I need to call, so I could have an interface for these methods, but also extend a base class to store all the attributes they will share, like X, Y, Sprite, things like that? And alternatively I could do that without the interface, just using an abstract class, but then I could face a lot of extra work if I need to change things later?
Offline philfrei
« Reply #6 - Posted 2011-12-19 09:42:14 »

What you describe is what I did in my game. It works for me.

I have an interface called "Animateable". It's attached to all classes that are animated. It has exactly those two methods: update() and draw(), as these are the two main steps in the game loop. Though in my game, I use a util.timer as the "game loop". A copy of every "animateable" object is stored in an Animateable[] and the timer iterates through them calling the updates() and the draws() in two passes. (Timers aren't very popular here, but everyone who has tried my game says the animation is smooth.)

Is it possible to have an animation that doesn't have an X & Y? I think the answer is yes. An object can change color or texture or size or in some other fashion. Therefore, it makes sense that the X & Y, which are properties of a thing, be part of the class definition, and sub-classed to objects that also have X & Y. Main thing I look out for is if subclasses start containing properties that they never use.

"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 Roquen
« Reply #7 - Posted 2011-12-19 13:32:15 »

Personally I consider the design model which sproingie is discussing to be a moderate to advanced topic, which IHMO (that's IMHO for the non dyslexic) is overused in practice.  Don't get me wrong, I totally subscribe to the notion of "composition over inheritance", 100% and without reservation. However, in the wild, I see usages which are greater complexity and lower flexibility than the simpler composition model of, well, composite classes.

OP:  Instead of answering your question, I'll pose one for you.  I'd say that if you have logical "things" that vary only by their data, then no new type is needed, so why are various specific NPCs different classes?  "Wait!", you might respond, "They have different behaviors and therefore code!".  "Ah ha!", I'd replay, "But by dear friend...code IS data!".

In an attempt to answer your question.  Abstract classes and interfaces are somewhat similar.  The difference is that interfaces never have (direct) state (fields).  Interfaces must be used in cases where putting an abstract class far enough up in inheritance chain is impossible or impractical.  Beyond that "proper" usage is subjective and context dependent. 
Offline ra4king

JGO Kernel


Medals: 322
Projects: 2
Exp: 4 years


I'm the King!


« Reply #8 - Posted 2011-12-19 20:47:31 »

Agreed with all the above except for one nitpick: I really don't recommend this "prefixing Interfaces with IFoo IBar IBlah" business.  The point of an interface is not to be special and call attention to itself as an interface, but to act as any other class would, and having a naming convention only for interfaces defeats the purpose.  It works well for COM because interfaces in COM really are distinct from classes, but nowhere in the JDK do you find interfaces using this convention, and frankly it's a mistake for .NET to have done it that way.
Hear hear!

Offline Catharsis

Junior Member




EGR Software rocks!


« Reply #9 - Posted 2011-12-20 09:07:44 »

I suppose I do this in my efforts for the core component architecture at least since it makes things clearer. You'd have to dig around some other posts to get all the background & "razmatazz".

componentManager.getAs(IActivityLifecycle.class) by naming convention alone makes it clear that one is dealing with an interface and not expecting code completion to any public member variables... I don't prepend shared / IE cross-platform J2SE / Android classes with "Shared" or J2SE. The actual cross-platform implementation or base class is "ActivityLifecycle" which may also be dual registered and accessed as componentManager.getAs(ActivityLifecycle.class) along with the interface. Likewise with the Android specific version: componentManager.getAs(AndroidActivityLifecycle.class). However for cross-platform usage things are composed using the interface and if direct access is necessaryfor any given component they are also stored under the actual implementation type.

In my case the naming convention helps shorten cross-platform implementation class names whether they are base classes or what not.

Technically devs using my efforts can do whatever they want for naming conventions, but I've found the prepend useful for interfaces and code readability in my core component architecture work. It's not for everyone nor a rule; use when handy essentially. Before my efforts went full on cross-platform I didn't standardize on prepending "I". I'd also argue it depends on the size of the project; less than 50-100 classes and small entity hierarchy then don't bother. While the core architecture is small w/ my efforts the larger network of components / libraries is growing beyond 1600 classes now with likely ~2k by the time I fully flush things all the way out feature wise; nice thing is it's highly modularized. Prepending "I" for interfaces just helps out at a certain scale, but to each their own.

Founder & Principal Architect; EGR Software LLC
http://www.typhonrt.org/
http://www.egrsoftware.com/
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.

xsi3rr4x (38 views)
2014-04-15 18:08:23

BurntPizza (34 views)
2014-04-15 03:46:01

UprightPath (50 views)
2014-04-14 17:39:50

UprightPath (32 views)
2014-04-14 17:35:47

Porlus (49 views)
2014-04-14 15:48:38

tom_mai78101 (71 views)
2014-04-10 04:04:31

BurntPizza (130 views)
2014-04-08 23:06:04

tom_mai78101 (230 views)
2014-04-05 13:34:39

trollwarrior1 (193 views)
2014-04-04 12:06:45

CJLetsGame (200 views)
2014-04-01 02:16:10
List of Learning Resources
by SHC
2014-04-18 03:17:39

List of Learning Resources
by Longarmx
2014-04-08 03:14:44

Good Examples
by matheus23
2014-04-05 13:51:37

Good Examples
by Grunnt
2014-04-03 15:48:46

Good Examples
by Grunnt
2014-04-03 15:48:37

Good Examples
by matheus23
2014-04-01 18:40:51

Good Examples
by matheus23
2014-04-01 18:40:34

Anonymous/Local/Inner class gotchas
by Roquen
2014-03-11 15:22:30
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!