can you call different methods with one changing variable in java? - java

ex:
public class Game{
String level;
public void update(){
update+"level"(); //calls diff. method depending on variable
}
public static void setLevel(String lv){
level = lv;
}
private updateLevelOne(){
.....
}
private updateLevelTwo(){
.....
}
}
public class Level{......
Game.setLevel(One);
}
I know the top statement wont work. But I was wondering if its possible to make a call in such way that I wouldn't have to use a if/switch statement and go directly to the method.

Either use a switch statement or objects:
Switch statement:
public class Game {
private int level;
public void update() {
switch(level) {
case 1:
updateLevelOne();
break;
case 2:
updateLevelTwo();
break;
}
}
public static void setLevel(int lv) {
level = lv;
}
private updateLevelOne() {
.....
}
private updateLevelTwo() {
.....
}
}
Alternatively, make your levels objects:
public class Game {
private Level[] levels;
private int currentLevel;
public Game() {
levels = new Level[2]
levels[0] = new Level();
levels[1] = new Level();
currentLevel = 0;
}
public void update() {
levels[currentLevel].update();
}
public static void setLevel(int newLevel) {
currentLevel = newLevel;
}
}
public class Level {
public Level() {
}
public void update() {
}
}
Objects are preferred but you can go either way. You could also go with the reflection package, but that's a worse idea that will be harder to understand.

No, it's not possible to create method names dynamically like this.
You should look up the Strategy pattern. This means you set some Level interface as a field in your class.
All your different levels should implement this interface, and each should implement some update method. At runtime, you can set this field with the exact implementation that you need at that time and you can call update() on it. This will delegate to the required implementation.

Related

Accessing child variables from super workaround

I have the following classes.
public abstract class Thing {
private String appearance;
public void setAppearance(String appearance) {
this.appearance = appearance;
}
}
public abstract class MovableThing extends Thing {
// ASCII representation of MovableThing moving right.
private static String FACE_RIGHT;
// ASCII representation of MovableThing moving left.
private static String FACE_LEFT;
private boolean goingRight;
public MovableThing() {
setAppearance(FACE_RIGHT);
goingRight = true;
// Some other things
public void turnAround() {
goingRight = !goingRight;
if (goingRight) {
setAppearance(FACE_RIGHT);
} else {
setAppearance(FACE_LEFT);
}
}
public class Bird extends MovableThing() {
private static String FACE_RIGHT = "/'/>";
private static String FACE_LEFT = "<\\'\\";
public Bird() {
super();
// Some other things
}
}
I know that this is currently incorrect because in MovableThing, FACE_RIGHT doesn't get assigned anything so when I call super() in Bird, the appearance just gets set to null. How can I work around this? I have multiple animals with different left/right ASCII representations but I'm not sure how to do all of this in an OOP kind of way.
Edit: Meant to say Bird() instead of Chicken().
Here is what I would do with your code to model your scenario:
public abstract class Thing {
private String appearance;
// Require subclasses of Thing to have a defined "going left" and "going right"
// method.
public abstract void setGoingLeft();
public abstract void setGoingRight();
protected final void setAppearance(String appearance) {
this.appearance = appearance;
}
}
public abstract class MovableThing extends Thing {
private boolean goingRight;
public MovableThing() {
setGoingRight();
// Some other things
}
// Require subclasses to define a method that gives me a String showing which
// way they're facing, when I tell them what way they're facing. This allows
// subclasses (like Bird) to each return their own appearances depending on the
// way they are facing.
protected abstract String getAppearance(boolean right);
// Override the "going left" and "going right" methods (and make them final so
// subclasses can't change them). These also modify the "goingRight" field of a
// MovableThing correctly.
#Override
public final void setGoingLeft() {
goingRight = false;
getAppearance(false);
}
#Override
public final void setGoingRight() {
goingRight = true;
getAppearance(true);
}
public void turnAround() {
// If they're going right, turning them around will make them go left and vice
// versa.
if (goingRight)
setGoingLeft();
else
setGoingRight();
}
}
public class Bird extends MovableThing {
private static final String FACE_RIGHT = "/'/>";
private static final String FACE_LEFT = "<\\'\\";
// This method is called by the super class.
#Override
protected String getAppearance(boolean right) {
// If the super class asks for a Bird's appearance when facing right, return
// "FACE_RIGHT". Otherwise, return "FACE_LEFT". (Other animals can return
// different things depending on the way they're facing.)
return right ? FACE_RIGHT : FACE_LEFT;
}
}

How to use advanced methods

So, I've been working on my method building with arguments and such, but I've come across a dillema. If I were to do this:
public static void setStat() {
}
Is it possible to create "Sub-Methods" in this case? I'll give an example:
public static int attack(int attack) {
return attack;
}
public static int defense(int defense) {
return defense;
}
Then tie the "Super Method" (setStat()) to the "Sub-Methods" like so:
setStat().attack(4);
If it is possible, please provide an example on how I could do this.
Then you have to return the current instance i.e. this from your setStat() method and it should be changed from ,
public static void setStat() {
}
To
public ThisClass setStat() {
//your logic
return this;
}
public int attack(int attack) {
return attack;
}
Then you can try to do this,
object.setStat().attack(4);
You can achieve this by moving your methods from static to instance methods and deal with current this object.

Passing parameter to anonymous class in Java

i'm trying to write anonymous inner class
interface Face{
void seeThis(String what);
}
class Eyes {
public void show(Face f){}
}
public class Seen {
public void test() {
Eyes e = new Eyes();
e.show(new Face() {
#Override
public void seeThis(String what){
System.out.print(what);
}
});
public static void main(String[] args) {
Seen s = new Seen();
s.test();
}
}
How to call seeThis() and how to pass parameter to it?
Method seeThis() belongs to Face class, which instance is anonymous and thus cannot be reached without storing reference to it. If you want to store a reference, you can do this in the following way:
public class Seen {
public Face face;
....
this.face = new Face() { ... };
e.show(this.face);
And then,
Seen s = new Seen();
s.face.seeThis();
Now, regarding passing the parameter. You have two options - declare parameter outside of anonymous class and make it final in order to be reachable by this anonymous class, or replace anonymous class with normal one and pass the parameter to its constructor:
Approach one:
final int parameter = 5;
...(new Face() {
#Override
public void seeThis() {
System.out.println(parameter);
}
});
Approach two:
public class MyFace implements Face() {
private final int parameter;
public MyFace(int parameter) {
this.parameter = parameter;
}
#Override
public void seeThis() {
System.out.println(parameter);
}
}
Then,
...
e.show(new MyFace(10));

Should I pass and store class references or make methods to get them from a central class?

I have a main class branching off to different classes which handle certain things.
Sometimes some of the classes need a method from a different class.
Currently I'm declaring and initiating the classes in my main class and then passing these objects to other classes that need them.
Example 1:
public class Main extends plugin {
private Walking walkClass;
private Sitting sitClass;
#Override
public void onEnable() {
walkClass = new Walking(this);
sitClass = new Sitting(this, walkClass);
}
//Methods
}
public class Walking {
Main mainClass;
public Walking(Main mainClass) {
this.mainClass = mainClass;
}
//Methods
}
public class Sitting {
Main mainClass;
Walking walkClass
public Sitting(Main mainClass, Walking walkClass) {
this.mainClass = mainClass;
this.walkClass = walkClass;
}
//Methods
}
Is okay to do this, or will it be better to create methods in the Central class to give references to other classes? In regards to Memory and CPU usage and Java practices.
Edit:
I'm comparing it to something like this;
Example 2:
public class Main extends plugin {
private Walking walkClass;
private Sitting sitClass;
private boolean started;
#Override
public void onEnable() {
started = true;
walkClass = new Walking();
sitClass = new Sitting();
}
public boolean isStarted() {
return started;
}
public Walking getWalking() {
return walkClass;
}
public Sitting getSitting() {
return sitClass;
}
}
public class Walking {
private Main mainClass;
private boolean walking;
public Walking(Main mainClass) {
this.mainClass = mainClass;
walking = mainClass.isStarted();
}
public boolean isWalking() {
if (mainClass.isStarted() {
return walking;
}
}
}
public class Sitting {
Main mainClass;
public Sitting(Main mainClass) {
this.mainClass = mainClass;
}
public boolean isSitting() {
return !mainClass.getWalking().isWalking();
}
}
I'm just worried that if I do it like in Example 1 and I store too many references to other instances it'll take up more memory than doing doing it like in Example 2.
Then if I do it like in Example 2, I'm worried that calling a method will add additional CPU tick(s) over if I did it as Example 1. I have no formal education in Java so I have no idea.
Though the fact that people would consider Example 1 the best practice is encouraging.

using object functions in java

I'm trying to implement function objects in Java. I have a Unit class, with a default addition function that should be used in most initializations of a Unit object. However, for some issues, I need a different addition function. The code will look something like this:
public class Unit() {
public Unit(unitType) {
if (unitType == "specialType") {
additionFunc = defaultFunc } else {
additionFunc = specialFunc }
}
}
public int swim() {
return additionFunc()
}
// definiion of regularFunc
// definition of specialFunc
}
Then, from the main file:
Unit fish = new Unit(regularTyoe);
Unit fatFish = new Unit(specialType);
fish.swim(); //regular function is called
fatFish.swim(); //special function is called
That's it.. does anyone know how this can be done?
You need to look up inheritance and method overriding. It would probably help to read up on proper Object Oriented Programming as well.
The proper way to do this is:
class Fish {
public void swim() {
// normal swim
}
}
class FatFish extends Fish {
#Override
public void swim() {
// special swim
}
}
Fish fish = new Fish()
Fish fatFish = new FatFish()
fish.swim() // normal swim
fatFish.swim() // slow swim
Make a new FatFish class which extends Unit and overrides swim().
Unit fish = new Unit();
Unit fatFish = new FatFish();
fish.swim(); //regular function is called
fatFish.swim(); //special function is called
There are many solutions for your problem, one of them is using inheritance, that you could have a default implementation of Unit, and extend it overriding the desired method with a new one.
Basically would be something like:
public class FatFish {
#Override
public void swim() {
// new behavior
}
}
Another approach would be to implement Strategy Design Pattern, which allows you to select algorithms on runtime. Therefore you could do something like:
public interface SwimStrategy {
void execute();
}
public class FatFishSwimStrategy implements SwimStrategy {
#Override
public void execute() {
// fat fish swim impl
}
}
public class FishSwimStrategy implements SwimStrategy {
#Override
public void execute() {
// normal fish swim impl
}
}
public class Fish {
private final SwimStrategy swimStrategy;
public Fish(SwimStrategy swimStrategy) {
this.swimStrategy = swimStrategy;
}
public void swim() {
swimStrategy.execute();
}
}
In order to instantiate an object you could do:
new Fish(new FatFishSwimStrategy());
or for the normal behavior:
new Fish(new FishSwimStrategy());
I think it can do by extends and factory method:
public class Unit {
public static Unit createUnit(UnitType type) {
if (UnitType.Special == type) {
return new Unit(type) {
#Override
public int swim() {
System.out.println("special swim");
return 0;
}
};
}
return new Unit(UnitType.Default);
}
private UnitType type;
private Unit(UnitType type) {
this.type = type;
System.out.println("create unit for " + type);
}
public int swim() {
System.out.println("default swim");
return 0;
}
public static void main(String[] args) {
Unit fish = Unit.createUnit(UnitType.Default);
Unit fatFish = Unit.createUnit(UnitType.Special);
fish.swim();
fatFish.swim();
}
}
This is a simple type enum:
public enum UnitType {
Default, Special
}
There are two ways to accomplish this polymorphic behavior in Java. The first is to use a inheritance and a hierarchical set of classes. For example, you could have an abstract base class which defines an abstract method called "swim". Then each concrete fish class would extend this base class and implement the swim method. Later when you have a set of fish objects, you can upcast them to the base class and invoke the swim method on each.
The second way is to use interfaces. You define an interface (e.g. ISwim) which declares the public method swim. Each fish class (whether part of a class hierarchy or no) would implement the ISwim interface, meaning they would define a swim method. Then if you have a set of fish class objects of different types, you can cast each to the ISwim interface and invoke the swim method on each object.
Java does not have function pointers, so the approach you are considering is inappropriate for the language. Even in languages with function pointers, the above two approaches would be most appropriate in my opinion.
One way to do this is with an enum for the types of Unit and with Unit subclasses:
public class Unit {
public enum UnitType {
REGULAR {
public Unit makeUnit() {
return new RegularUnit();
}
},
SPECIAL {
public Unit makeUnit() {
return new SpecialUnit();
}
};
abstract public Unit makeUnit();
}
protected Unit() {}
public abstract int swim();
private static class RegularUnit extends Unit {
RegularUnit() {}
public int swim() {
return 0;
}
}
private static class SpecialUnit extends Unit {
SpecialUnit() {}
public int swim() {
return 1;
}
}
}
Unit fish = UnitType.REGULAR.makeUnit();
Unit fatFish = UnitType.SPECIAL.makeUnit();
Another way is with Callable objects:
public class Unit {
public enum UnitType { REGULAR, SPECIAL }
private Callable<Integer> additionFunc;
public Unit(UnitType type) {
switch (type) {
case REGULAR:
additionFunc = new Callable<Integer>() {
public Integer call() {
return 0;
}
};
break;
case SPECIAL:
additionFunc = new Callable<Integer>() {
public Integer call() {
return 1;
}
};
break;
}
}
public int swim() {
return additionFunc();
}
}
Using a simple if statement:
private String unitType;
public Unit(unitType) {
this.unitType = unitType;
}
public int swim() {
if (unitType.equals("specialType") {
return specialFunc();
}
else {
return regularFunc();
}
}
Or using polymorphism and a factory method :
public abstract class Unit() {
protected Unit() {
}
protected abstract int addition();
public int swim() {
return addition();
}
public static Unit forType(String unitType) {
if (unitType.equals("specialType") {
return new SpecialUnit();
}
else {
return new RegularUnit();
}
}
private static class SpecialUnit extends Unit {
#Override
protected addition() {
// special addition
}
}
private static class RegularUnit extends Unit {
#Override
protected addition() {
// regular addition
}
}
}
Or using an Adder functional interface, defining an addition() method, and two concrete implementations of this interface:
private Adder adder;
public Unit(unitType) {
if (unitType.equals("specialType") {
this.adder = new SpecialAdder();
}
else {
this.adder = new RegularAdder();
}
}
public int swim() {
return adder.addition();
}
This last one is the closest to waht you asked in your question. function objects don't exist per se, but can be replaced by interfaces.

Categories

Resources