Creating objects with different properties from one class - JAVA - java

In Java, I have an abstract class Player and the two classes Striker and Defender they both extend the abstract class Player. I have an Interface IAttack and an Interface IDefend. In those 2 interfaces there is the prototype of only one method - the method shoot(for the Interface IAttack) and the method tackle(for the interface IDefend). I've implemented the method shoot(resp. tackle) in the class Striker(resp Defender).With this hierarchy I can create Strikes, who can only shoot the ball to a given distance. I can create defenders, who can tackle somebody only with a given intensity.
What I want is to be able to create strikers(resp. defenders) who can do different tasks(and not only shoot to a given distance). For example I'd like to have a striker who can shoot a penalty, a striker who can play with its head etc.
How can I do that? Do I need necessarily to create more classes for the strikers(I mean a class for the strikers who shoot penalties, a class for the striker who play with head). Is there a more elegant way to have strikers who can do multiple tasks?

Couple of ways to implement it.
1) Let another Stricker class implement both IShootPenalty, and IAttack behavior. You can create individual required interfaces, and let each player object implement appropriate interfaces. Mix and match them as required.
(or)
2) Create boolean flags for each behavior in abstract class, and set the appropriate flags based on required behavior.
Stricker.setShootPenality(true);
Striker.setShooter(true);

A nice way would be to have all the properties in a different class.
Say for example, a class called StrikerProperties.java.
You can have different variables here and set them true or false depending upon the other characteristics of the player. This will enable you to use this for different objects, and also different classes, in cases you want to make teams and all later.

Related

Alternatives to a deep & narrow inheritance hierarchy?

(Novice Java developer here, any responses would be greatly appreciated.)
I have created an implementation of a game, and several different AI's that play it. Lets say they all use the same base algorithm, something like Monte-Carlo Tree Search (MCTS). All of the AI's share this common template, but they all have slight differences. Each AI must contain the previous AI's modifications as I must demonstrate my progress.
Currently, I have an interface which defines the required methods of MCTS and an abstract class which defines implementations of these methods to perform vanilla MCTS (Unoptimised). The first AI I created extends this abstract class to define a concrete version. Then the next AI extends the first and overrides certain methods to modify the algorithms behaviour in some way. This kind of process is repeated so each AI extends the previous one, gaining previous alterations and defining its own.
This creates a deep and narrow like inheritance hierarchy, which has a consequence of being hard to understand. Is there a better way to create these AI's and change the inheritance hierarchy?

How do I write a method that has the same implementation for multiple kinds of objects (Java)?

I am writing a (currently) String-based Pokemon game in Java. With the structure I have, there are currently 2 kinds of objects that I want to do Type matchups for: Pokemon and moves. The method I want to write (isStrongAgainst()) would be the same for both. For example, a water type pokemon and a water type move are strong against fire type Pokemon, but these comparisons can imply different things based on context. Both classes have differently implemented isType() methods.
The idea I had was to use an interface that implements a default isStrongAgainst() method and declares an abstract isType() method. I would think that since any class that implements this interface would have to implement isType(), I could use it in my isStrongAgainst(), but I cannot. Is there any way around this or a better suggestion given my problem?
public interface TypeMatch<T> {
boolean isType(Type t);
default boolean isStrongAgainst(Pokemon opponent){
if(T.isType(Type.NORMAL)){
return false;
}
if(T.isType(Type.WATER)){
return opponent.isType(Type.FIRE) ||
opponent.isType(Type.ROCK) ||
opponent.isType(Type.GROUND);
} //etc...
As far as understand, your game contains different behaviors according to type of a Pokemon. I highly recommend you to use strategy design pattern.
What I think is that the isStrongAgainst() function can be refined more.
It would better to make an implementation of isType() in such a way that it returns true if the opponent is weaker than us.
This can then be used in the function isStrongAgainst() directly in its return statement.
Best
PS: I am in class right now and I will give a more detailed answer after I’m over with it, till then if possible try to get some idea of what I have said.
You may:
define Pokemon as an abstract class to implement TypeMatch
move isStrongAgainst(Pokemon opponent) from TypeMatch to Pokemon.
any class that extends Pokemon has the same implementation of isStrongAgainst(Pokemon opponent)

Java Game Development, working with "Classes"

I've been developing a small text-based RPG game in Java. I've written a story-line and did inventory/armor equipment. I've ran into a problem when it comes to accessing some code though. At the beginning of the game, the user can choose to be an archer/mage/warrior (i'll refer to these as "Jobs" not "class"). Each of these have their own class. But when incorporating them into the game, I find that i'm doing a lot of if-statements to always check if the user is a archer/mage/warrior.
How would I better integrate this without using if-statements everywhere? I'm a beginner/intermediate level and doing Objects for about a month now.
It would be easiest to use polymorphism for this, but this isn't possible if the methods have different names...
If you wanted to do this polymorphically:
First off, read up on polymorphism. Here's a good website to do that.
To start off, have all of your classes extend a superclass, say Player (you will have to write the Player class before you can extend it). To extend the Player class, you can write something like this in the header of your "job" classes:
public class Mage extends Player {
Of course, you substitute Mage for the different classes depending on what "job" you're defining.
Inside the Player class, which you will have to write, you should define all of the methods you want your subclasses to be able to execute. You should make these methods abstract, but keep in mind, if you have an abstract method, you will have to define it in ALL of your subclasses. So, if you had a abstract method called "Cast" you would need to define this in EVERY "job" class.
But once you have created a superclass, with methods, (I suggest having general abstract methods such as Attack or Defend), just define these methods in the subclasses, and you're good to go.
If you want to do this non-polymorphically:
An if-statement, while not necessarily pleasant, appears to be the most effective way to do this, if you don't want to try to make the behaviors polymorphic.
Could you say what the structure of your if-statement is? There might be an easier way to write it, and cut down on the amount of code (to make it more legible).
For example, if you are saying:
if (a.getClass() == X.class)
You could consider using instanceOf instead:
if (a instanceof X)
Besides this, I don't have any better ideas on how to do this.

How to achieve multiple inheritance in java

I am designing Traveller App. For which I need to design 'Traveller' class and with its instance I should be able to access properties of different types of Travel modes.
class Traveller {
// common properties.
}
class RoadTravel {
// properties specific to class
}
class WaterTravel {
// properties specific to class
}
class RailTravel {
// properties specific to class
}
from the above code , I just want to create instance of 'Traveller' class and should be able to access the properties of all other classes (RoadTravel,WaterTravel,RailTravel).
I dont want to create any dependency on my sub classes and also my instance variables should not be final.
Please suggest good way of implementation so that it should be easy to add any new type of Travel mode in future.
In Java you cannot have a class which extends (inherits) from multiple classes. (You might want to look into the Deadly Diamond of Death Problem.
In your case, what you could have would be a Travel interface which defines the behaviour each of your travel types need to expose, such as cost(int duration), getName(). etc/
Your logic would then use the Travel interface to do it's logic. The travel type dependent logic would be stored in the seperate classes which make use of the Travel interface. Your main logic would then delegate travel specific logic to these classes which are passed to it at run time.
You will need to take a look at the Strategy Design Pattern to see how you can implement this.
A way to implement multiple inheritance in java is the use of proxies.
Your requirements do not seem very clear and so I cannot suggest a complete solution.
If you provide an example of client code that will use these classes, I can suggest in more details how to implement it using proxies.

Use of Java [Interfaces / Abstract classes] [duplicate]

This question already has answers here:
Interface vs Abstract Class (general OO)
(36 answers)
Closed 9 years ago.
Lately i decided to take a look at Java so i am still pretty new to it and also to the approach of OO programming, so i wanted to get some things straight before learning more, (i guess it's never to soon to start with good practices).
I am programming a little 2D game for now but i think my question applies to any non trivial project. For the simplicity I'll provide examples from my game.
I have different kinds of zombies, but they all have the same attributes (x, y, health, attack etc) so i wrote an interface Zombie which i implement by WalkingZombie, RunningZombie TeleportingZombie etc. Is this the best thing to do? Am i better of with an abstract class? Or with a super class? (I am not planning to partially implement functions - therefor my choice for an interface instead of an abstract class)
I have one class describing the main character (Survivor) and since it is pretty big i wanted to write an interface with the different functions, so that i can easily see and share the structure of it. Is it good practice? Or is it simply a waste of space and time?
I hope this question will not be rated as subjective because i thought that experienced programmers won't disagree about this kind of topic since the use of interfaces / super classes / abstract classes follows logical rules and is thereby not simply a personal choice.
You can think of an interface as a "contract". You are defining a set of methods that classes which implement this interface must implement.
An abstract class, on the other hand, is used when you have some code that could be common to all the child classes you want to implement. So you might have an abstract class called Shape that has some common code, and in your derived classes (Circle, Square, etc.) you could have the code that is specific to those shapes (getArea would be an example). But something like color might be common to all shapes, so you could put a getColor method in your Shape abstract class.
And you can combine the two ideas. You can have abstract classes which implement interfaces, and this gives you the best of both worlds.
These concepts are used over and over again in OO, so it's important to understand them. You seem to be well on your way :).
So if your zombie class has some common behavior that applies to all types of zombies, it sounds like a good candidate to be an abstract class. You could also consider creating an interface (maybe a GameCharacter interface) if you have other characters in your game (maybe UndeadMice or something :)). Then your Zombie abstract class and UndeadMouse abstract class would implement the GameCharacter interface.
When in doubt, I choose to follow the GOF paradigm.
Encapsulate what varies: - Define unique behavior in its own class. To refer the above example, implement behaviors for walking, running and teleportation in its separate class. This way, polymorphic behavior is implemented.
Conversely, **Aggregate what is common** - Use Abstract classes to define common behavior in polymorphic associations. I use these principles when designing relationships between objects.
Yes, I think you're heading down the right track with interfaces over abstract classes.
Any concrete Zombie you might want to make could possess any combination of the Walking, Running or Teleporting features you care to implement.
I think modern programming theory discourages inheritance as much as possible, because it inhibits reusability and flexibility in the long-run. Rather, use interfaces and composition to achieve flexibility without 'tight coupling'.
One methodology to re-use code without inheritance, you could apply the 'Favour composition over inheritance' paradigm.
I like to think Josh Bloch's 'Effective Java' (2nd edition) can be taken as "current thinking" ...
http://books.google.com/books?id=ZZOiqZQIbRMC&pg=RA1-PA71&lpg=RA1-PA71&dq=%22Bloch%22+%22Effective+java:+programming+language+guide%22+&hl=de&sig=RxlDlRBWUvNAzsAFzqOcftrYI5E#v=onepage&q&f=false
So, you could implement all your behaviours as independent classes, and then give each zombie implementation its own combination of behaviours, through implementation & composition..
Hope that makes sense & helps ...
I would have written Zombie as an abstract class to avoid the redefinition of the fields x, y, health, etc...
For the Survivor class, I would simply have declare public the functions to be used externally. I declare public functions at the top of the class. Declaring an interface when there is only one class implementing it uselessly adds a file to maintain. Avoid it.
Nobody agrees about the use of interfaces over super/abstract classes ;)
The main reason to use interfaces and super/abstract classes is to enable polymorphism. In your case for instance, you have stuff moving on the screen (the player and the zombies and so on). Why not make them all move on the screen using the same method? Maybe inherit everything that's going to move on the screen from an object called "Movable" or something like that.
And if you're really into this stuff you might want to look at mixins as well. It's not something that Java supports directly but there are libraries built for it.
I have different kinds of zombies, but they all have the same attributes (x, y, health,
attack etc) so i wrote an interface Zombie which i implement by WalkingZombie,
RunningZombie TeleportingZombie etc. Is this the best thing to do? Am i better of with an
abstract class? Or with a super class?
an abstract class will be a super class for your zombies. an interface would also in some sense be a super class (super interface?) for your zombies.
the common properties suggest at least an abstract base class for common properties.
(I am not planning to partially implement functions - therefor my choice for an interface
instead of an abstract class)
not sure what you mean by this.
if you had different kinds of monsters (goblins, orcs, etc.) you might find behaviour common to these that would want to belong to different base classes. this would suggest an interface.
i would start with an abstract base class and see what the code tells you as you write it.
I have one class describing the main character (Survivor) and since it is pretty big i
wanted to write an interface with the different functions, so that i can easily see and
share the structure of it. Is it good practice? Or is it simply a waste of space and
time?
your survivor is what is called a player-character (as opposed to a non-player character - someone in a game who will normally not attack your survivor).
most games treat all of these character types as some kind of monster since they will all have many properties in common (health. magic, treasures, weapons, etc.)
so perhaps that's more of an argument for an interface.
see:
Using inheritance and polymorphism to solve a common game problem
Class diagram examples for RPG (Role Playing Game)
designing class hierarchy for typical characters in role playing game
I don't think that in your case your interface and class structure aligns well with the reality. In fact, I believe (correct me if I'm wrong) that each zombie can be walking, running, teleporting etc. depending on where it is.
Therefore, you should have a zombie class or interface and have actions which modify the zombie's state. The action would probably be an interface or an abstract class, so that you can apply any action to a zombie without knowing what the exact action does (e.g. action.perform(zobie)).
If you have different kinds of zombies, such as three-legged-zombie and one-armed zombies, you might want to implement different classes which handle the zombie stuff, such as displaying themselfes or validating state changes (e.g. a special kind of zombie may not accept to be teleported).
in terms of your Zombie example, the interface will do well, unless you have common code that you want all zombies to do.
Say you have a Move method, that makes walkingzombies walk, runningzombies run, etc. However, if you want "Move" to make any kind of zombie do something common, then the interface is going to force you to duplicate code, as you cant put a body in an interface.
My opinion is you better use abstract class called Creature as a super class for all type of, well, creatures, and extend it to Zombie for all type of zombies.
And you will also need an interface.. to define what are the things that a creature can do..
like maybe, walk, or claw, or scream...
the reason why you need an abstract class is to disable the instantiation of Creature, you wouldn't want to have a creature without knowing what creature it is, right?

Categories