Abstract methods without abstract classes - java

I'm kinda new to Java, and I'm trying to write an RPG of sorts.
Now, in the game the player character would have skills. These could be very diverse, from hurting enemies to healing the player and a lot of other things. It'd make sense to create a Skill class with an abstract applyEffect() method, to be defined on each particular skill.
However, I cannot have a non-abstract class containing abstract methods, and every skill should be an object of the Skill class, so it can't be abstract. The obvious solution is to make the Skill class abstract and create a subclass for every single skill, and then instantiate that into an object to use.
This approach seems a bit redundant. Is there anything else I could conceivably do in this situation?
EDIT: While we're at it, if I want an object that will appear a single time with standard variables, is there any workaround to making a class just for that one object and then instantiating it?

I would not write skills (like 'heal' and 'hide') as classes. I view classes as objects (players), and methods as abilities (skills). Skills like 'heal' or 'hide' are clearly better as methods than classes.
I would simply have one class that has all methods, but only the selected ones are available for use. Having the skills as enums isn't a bad idea either.
enum Skill {
HEAL, HIDE, ATTACK, THROW
}
class Player {
boolean canHeal = false;
boolean canHide = false;
boolean canAttack = false;
boolean canThrow = false;
Player(Skill[] skills) {
for(skill : skills) {
switch(skill) {
case Skills.HEAL: canHeal = true;
break;
case Skills.HIDE: canHide = true;
break;
case Skills.ATTACK: canAttack = true;
break;
case Skills.THROW: canThrow = true;
break;
default: //error
}
}
}
void heal() {
[...]
}
void hide() {
[...]
}
void attack() {
[...]
}
void throw() {
[...]
}
boolean canHeal() {
return canHeal;
}
boolean canHide() {
return canHide;
}
boolean canAttack() {
return canAttack;
}
boolean canThrow() {
return canThrow;
}
}
Now the players can be restricted to only use the methods that should be available to them. What I would do is probably to write a GameHandler-class to take care of everything and do all the checking there.

How about this:
public abstract class Skill {
public abstract void applyEffect();
}
... somewhere else ...
Skill dig = new Skill() {
#Override
public void applyEffect() {
doSomeDigging();
}
};
This one still creates a subclass in the background, but you might like it better.

i would use enums also, you can stuff a bunch of login in them. the maps let each player have whatever skills and stats they need. you can nest enums like this or that.
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;
public class So36107587 {
enum Stat {
food,health,magic;
}
enum Skill {
heal,hurt,hunt;
static void apply(Skill skill,double amount,Player player) {
double a=amount*random.nextDouble(),x;
switch(skill) {
case heal:
x=player.stats.get(Stat.health);
player.stats.put(Stat.health,a+x);
break;
case hurt:
x=player.stats.get(Stat.health);
player.stats.put(Stat.health,a-x);
break;
case hunt:
x=player.stats.get(Stat.food);
player.stats.put(Stat.food,a+x);
break;
}
}
static final Random random=new Random();
}
static class Player {
Player() {
init();
}
void init() {
for(Stat stat:Stat.values())
stats.put(stat,1.);
for(Skill skill:Skill.values())
skills.put(skill,1.);
}
void apply(Skill skill,Player player) {
Skill.apply(skill,skills.get(skill),player);
}
#Override public String toString() {
return ""+skills+" "+stats;
}
final Map<Stat,Double> stats=new TreeMap<>();
final Map<Skill,Double> skills=new TreeMap<>();
}
public static void main(String[] args) {
Player player=new Player();
System.out.println(player);
player.apply(Skill.heal,player);
System.out.println(player);
player.apply(Skill.hunt,player);
System.out.println(player);
}
}

Related

over reliance on one arrayList

public class InventorySetDAO{
public LinkedList<CustomInventory> inventories = new LinkedList<>();
}
I am developing plugin that add/delete data in arraylist. and There's too much reference on the arrayList from other class.
Class InventoryItemModifier:
public class InventoryItemModifier {
InventorySetDAO inventorySetDAO;
public InventoryItemModifier(InventorySetDAO inventorySetDAO){
this.inventorySetDAO = inventorySetDAO;
}
public void addItem(ItemStack itemStack, ClickAction click, RequiredItems requiredItems) {
Bukkit.getPluginManager().callEvent(new ItemAddedEvent());
inventorySetDAO.getLastInventory().addItem(itemStack, click, requiredItems);
}
public void removeItem(ItemStack itemStack){
Bukkit.getPluginManager().callEvent(new ItemRemovedEvent());
inventorySetDAO.getLastInventory().removeItem(itemStack);
}
}
Class InventoryPlayerAccessor:
public class InventoryPlayerAccessor {
InventorySetDAO inventorySetDAO;
public boolean openPage(Player player) {
if (!inventories.isEmpty()) {
inventories.get(0).openInventory(player);
return true;
}
return false;
}
public boolean openPage(Player player, int index) {
if (!inventories.isEmpty()) {
if (index >= 0 && index < inventories.size()) {
inventories.get(index).openInventory(player);
return true;
}
}
return false;
}
}
I think there is risk of manipualte arrayList unproperly, so I think arrayList must be in a class and provide methods(add/insert/remove...) but if then there are too much responsibilities in that class.
I tried to seperate them into multiple classes, but it doesn't seem to solve this problem. is there a way to reduce reliance on arrayList, or efficient way to encapsulate arrayList?
To reduce each classes reliance on the underlying ArrayList (or just List), you could think about using the composite pattern instead of the DAO pattern. This would hide all/most of the logic to the InventorySet class.
class InventorySet {
private final List<CustomInventory> inventories = new ArrayList<>();
public void addItem() { }
public void removeItem() { }
}
Then, you can just keep your InventoryPlayerAccessor (maybe rename) but compose it of a InventorySet for easy access.
class InventorySetView {
void open();
}

Calling a method originated from a switch case from another class

I am relatively new to java and I have been assigned a project. I need to make a rather complicated(for a newbie) battleship game.
Here, I try to call switch cases in class Player from class Tile. Since I've read that one can't directly have access to a switch case, I have made the methods caseSea(), caseShip() e.t.c.
When trying to call them in class Player I get a 'void' type not allowed here error, which I understand but have no idea how to fix!
Any help would be appreciated thanks!
Here is class Tile created to represent one block of a 2D array that will become the battleground board:
public class Tile
{
private int x,y;
static boolean hidden;
public Action tile_action;
public enum Action
{
Sea,
Ship,
Hit,
Miss
}
Action action;
public Tile(Action action)
{
this.action=action;
this.x = x;
this.y = y;
this.tile_action = action;
}
public static void caseSea()
{
System.out.println("~");
}
public static void caseShip()
{
if(hidden == true)
System.out.println("~");
else
System.out.println("s");
}
public static void caseHit()
{
System.out.println("X");
}
public static void caseMiss()
{
System.out.println("O");
}
public static void draw(Action action)
{
switch(action)
{
case Sea:
caseSea();
break;
case Ship:
caseShip();
break;
case Hit:
caseHit();
break;
case Miss:
caseMiss();
break;
}
}
}
Also here is class Player which contains the call to the switch case:
import java.util.Scanner;
public class Player
{
String username; //Variable declaration
static int shotcount;
static int misscount;
static int hitcount;
static int repeatshot;
private int HitPosition[][] = new int[10][10];
public Player(String username)
{
this.username = username;
}
private void placeAllShips()
{
//super.placeAllShips();
}
public void fire(int pos[],int board,boolean hit)
{
if(hit == true)
{
HitPosition[pos[0]][pos[1]] = Tile.draw(Tile.caseHit());
shotcount++;
hitcount++;
}
else
{
HitPosition[pos[0]][pos[1]] = Tile.draw(Tile.caseMiss());
shotcount++;
misscount++;
}
}
}
I get the error that I mention above, in Tile.draw(Tile.caseHit()) and Tile.draw(Tile.caseMiss())
Heh, since this is a relatively simple issue I wanted to stick to comments, but I feel I need to make my voice since the other answers are simply wrong.
What the other guys are suggesting is changing the return type of the methods, and that indeed can work but not with the code you have.
They would ultimately be called twice, and thats not what you want.
The call order would be
caseHit()
pass the caseHit()'s value to draw()
enter a switch inside the draw() method with the Hit enum value and ultimately call caseHit() again.
This is not what you want to do. All you wanna do is call the draw() method with the right argument, which in this case is one of the Action enum values.
So ultimately there is a very easy way to fix your code without much changes and this is changing
Tile.draw(Tile.caseHit());
to
Tile.draw(Tile.Action.Hit);
(and by analogy the other calls of this method)
With Tile.draw(Tile.caseHit()) you are trying to call the caseHit() method and sending the return value of that method as a parameter to the draw() method. The problem is that the caseHit() method isn't returning anything as it has a void return type.
You could fix this by making the caseHit() method return an Action:
public static Action caseHit() {
return Action.Hit;
}

How can a static method change a variable? (Java)

I have this class:
class Inventory {
boolean smallknife = false;
boolean SRLockerkey = false;
void checkinv () {
System.out.println("You have the following items in your inventory: ");
System.out.println(smallknife);
System.out.println(SRLockerkey);
}
}
The Inventory test class
class InvTester {
public static void main(String args[]) {
Inventory TestInv = new Inventory();
System.out.println("This program tests the Inventory");
SKTrue.truth(TestInv.smallknife);
TestInv.checkinv();
}
}
and this class with a method to try to change the inventory
class SKTrue {
static boolean truth(boolean smallknife) {
return true;
}
}
class SKTrue {
static void truth(boolean smallknife) {
smallknife = true;
}
}
I would like to avoid using TestInv.smallknife = SKTrue.truth(TestInv.smallknife) and still change the variable but with a method. Is there a way that this can be done? I want that the truth method does the variable changing and I don't want to do the pass by reference part in the Inventory Test class. Thanks. Is there a way to do this in Java? (I also tried the second version which I think makes more sense)
Assuming you don't want to reference the variables directly (i.e. TestInv.smallknife = blah), the best practice in Java is to declare the variables as private and access them by getters/setters, e.g.:
class Inventory {
private boolean smallknife;
public boolean isSmallknife() {
return smallknife;
}
public void setSmallknife(boolean smallknife) {
this.smallknife = smallknife;
}
}
Now, you can do this:
Inventory TestInv = new Inventory();
TestInv.setSmallknife(SKTrue.truth(blah));
It is called Encapsulation, you can read more about it here.

enum singleton, referenced by interface, instance by string name

Thanks for viewing my question, which I have not successfully found an answer for in my searches/books. I'm learning java by writing a roguelike, but I think this question is more java-related than game-related. Feel free to educate me if I'm wrong.
I have similar classes that I want to each have specific abilities. The abilities are enum singletons with a set of standard method names that I would pass the Actor to - I wanted to avoid implementing methods from an interface in every Actor class, and just really liked the envisioned use of this approach as I go forward. I come from a shell/perl background and can't tell if I'm just not thinking OOP, or if I'm on to something useful and don't have the skills yet to pull it off.
addAbility(String) in StdActor is where it finally broke in this experiment.
Question is - am I doing something wrongheaded here? If not, how could I implement this?
interface for manipulating abilities:
public interface ActorAbility {
// doesn't work, but need something to enable
// instance retrieval for addAbility...
public ActorAbility getInstance();
public void act(Actor actor);
public boolean isTickable();
}
sanitized implementation of interface:
public enum ActorMove implements ActorAbility {
INSTANCE;
private ActorMove() {
}
public ActorAbility getInstance() {
return INSTANCE;
}
public void act(Actor actor) {
log.debug("Move");
}
public boolean isTickable() {
return true;
}
}
sanitized use of the ability. trial and error run amock. addAbility(String) broken, copy/paste from SO and elsewhere. it probably needs to be nuked from orbit.
public class StdActor implements Actor {
private HashSet<ActorAbility> abilities = new HashSet<>();
// this whole method is wrecked
public void addAbility(String ability) {
// Class<? extends ActorAbility> action; // in a maze of twisty passages...
ActorAbility actionInstance = null;
try {
// action = Class.forName("game3.Actors.Abilities." + ability);
actionInstance = ActorAbility.valueOf("game3.Actors.Abilities."
+ ability);
} catch (Exception e) {
e.printStackTrace();
}
this.abilities.add(actionInstance);
}
}
use case:
public class StdCharClass extends StdActor {
public StdCharClass() {
// I like this because it's clean and easily
// changeable
addAbility("ActorMove");
}
}
future planned use:
HashSet<ActorAbility> abilities = actor.getAbilities();
for (ActorAbility ability : abilities) {
if (ability.isTickable()) {
ability.act(actor);
}
}
Thanks!
EDIT:
Thanks for such a quick comment, JB. I tried what you suggested and it appears to do what I was hoping. It appears I was just off in the weeds and needed to be pulled back.
new class:
public enum Ability {
MOVE(ActorMove.INSTANCE), FIGHT(ActorFight.INSTANCE);
private ActorAbility ability;
private Ability(ActorAbility abilityClass) {
this.ability = abilityClass;
}
public ActorAbility getAbility() {
return this.ability;
}
}
StdActor:
public class StdActor implements Actor {
private HashSet<Ability> abilities = new HashSet<>();
public void addAbility(Ability ability) {
this.abilities.add(ability);
}
subclass:
public class StdCharClass extends StdActor {
public StdCharClass() {
addAbility(Ability.MOVE);
}
}
and finally, usage:
HashSet<Ability> abilities = bob.getAbilities();
for (Ability ability : abilities) {
ActorAbility abilityClass = ability.getAbility();
if (abilityClass.isTickable()) {
abilityClass.act(bob);
}
}
output!
12:44:15.835 [main] DEBUG ActorMove - Move

Enum within an enum

This isn't a matter of me being stuck, but rather I'm looking for a tidy way to write my code.
Essentially, I'm writing an event driven application. The user triggers an event, the event gets sent to the appropriate objects, and the objects handle the events. Now I'm working on writing the even handler methods, and I was hoping to use switch statements to determine how to handle the event. Right now whilst I'm working on the general structure, the event class is really simple:
public class Event {
public static enum Action {
MOVE, FOO, BAR
}
private Action action;
private int duration;
public Event(Action action, int duration) {
this.action = action;
this.duration = duration;
}
public Action getAction() {
return action;
}
public int getDuration() {
return duration;
}
Then, in another class, I'll have something like:
public void handleEvent(Event evt) {
switch(Event.getAction()) {
case MOVE: doSomething(); break;
case FOO: doSomething(); break;
case BAR: doSomething(); break;
default: break;
}
}
What I would like to do is something like this (though I would of course stick the switch statements into their own functions to avoid it turning into a nasty hairball of switches and cases):
public void handleEvent(Event evt) {
switch(Event.getAction()) {
case MOVE: switch(Event.getAction()) {
case UP: break;
case DOWN: break;
case LEFT: break;
case RIGHT: break;
}
case FOO: break;
case BAR: break;
default: break;
}
}
So, I'd want to create nested enums... like so:
public static enum Action {
public enum MOVE {UP, DOWN, LEFT, RIGHT}, FOO, BAR
}
It's not like I can't avoid the scenario, it would just be... convenient. So whilst the above doesn't actually work, is there some similar method to achieve this? It would be nice if I could send an event with the action "MOVE.UP", and the method would identify it first as an action of type MOVE, and then further identify that it is specifically in the UP direction. That's just a simple example, it would be grat if I could also make longer chains, something like "DELETE.PAGE1.PARAGRAPH2.SENTENCE2.WORD11.LETTER3". The way I see it, I'm just going to have to use Strings and lots of if/else statements. Hoping there's a better way! (Oh, and performance matters in my case, if that helps)
I believe that in Java, you can simply nest enums, as long as your non-enum constants come first.
enum Action
{
FOO,
BAR;
enum MOVE
{
UP,
DOWN,
LEFT,
RIGHT
}
}
This compiles for me and gives me the behavior you were looking for.
Perhaps use an inheritance hierarchy for the Events?
So you have:
- abstract Event
-- MoveEvent(Direction)
-- FooEvent()
-- BarEvent()
It may make more sense to have:
- abstract Event
-- abstract MoveEvent
--- MoveUpEvent
--- MoveDownEvent
--- MoveRightEvent
--- MoveLeftEvent
-- FooEvent
-- BarEvent
If all the Move events have a distance, then pass that into the MoveEvent constructor (which will ripple down).
you can nest them in an arbitrary order like this:
package nested;
import java.util.*;
import nested.Citrus.Orange;
interface HasChildren {
Set<Enum<?>> children();
}
enum Citrus implements HasChildren {
lemon, lime, orange;
Set<Enum<?>> children;
enum Orange implements HasChildren {
navel, valencia, blood;
Set<Enum<?>> children;
enum Navel implements HasChildren {
washinton, lateLane, caraCaraPink;
public Set<Enum<?>> children() {
return null;
}
}
static {
navel.children = new LinkedHashSet<Enum<?>>();
navel.children.addAll(EnumSet.allOf(Navel.class));
}
enum Blood implements HasChildren {
moro, taroco;
public Set<Enum<?>> children() {
return null;
}
}
static {
blood.children = new LinkedHashSet<Enum<?>>();
blood.children.addAll(EnumSet.allOf(Blood.class));
}
public Set<Enum<?>> children() {
return children != null ? Collections.unmodifiableSet(children) : null;
}
}
static {
orange.children = new LinkedHashSet<Enum<?>>();
orange.children.addAll(EnumSet.allOf(Orange.class));
}
public Set<Enum<?>> children() {
return children != null ? Collections.unmodifiableSet(children) : null;
}
}
public class EnumTreeNested {
static void visit(Class<?> clazz) {
Object[] enumConstants = clazz.getEnumConstants();
if (enumConstants[0] instanceof HasChildren)
for (Object o : enumConstants)
visit((HasChildren) o, clazz.getName());
}
static void visit(HasChildren hasChildren, String prefix) {
if (hasChildren instanceof Enum) {
System.out.println(prefix + ' ' + hasChildren);
if (hasChildren.children() != null)
for (Object o : hasChildren.children())
visit((HasChildren) o, prefix + ' ' + hasChildren);
} else
System.out.println("other " + hasChildren.getClass());
}
static <E extends Enum<E> & HasChildren> Set<E> foo() {
return null;
}
public static void main(String[] args) {
System.out.println(Citrus.Orange.Navel.washinton);
visit(Citrus.lemon, "");
System.out.println("----------------------");
visit(Citrus.orange, "");
System.out.println("----------------------");
visit(Citrus.class);
System.out.println("----------------------");
}
}

Categories