Is it possible to reference an abstract class method in a class method that does not extend it?

I take a tutorial on creating simple Ai behavior. The brain class is abstract and contains states like running, success, failure. Now in my ai - droid class, I have a way to start the droid brain.

public void update(){ if(Routine.getState()==null){ Routine.start(); } Routine.act(this, board); } 

Now this is not possible in java because it is a static reference to a non-static method. The usual abstract class that I am trying to do here is as follows:

 public abstract class Routine { public enum RoutineState{ Success, Failure, Running } protected RoutineState state; protected Routine() { } public void start(){ this.state = RoutineState.Running; } public abstract void reset(); public abstract void act(droid droid, board board); public void succed(){ this.state = RoutineState.Success; } public void Fail(){ this.state = RoutineState.Failure; } public boolean isSuccess(){ return state.equals(RoutineState.Success); } public boolean isFailure(){ return state.equals(RoutineState.Failure); } public boolean isRunning(){ return state.equals(RoutineState.Running); } public RoutineState getState(){ return state; } } 

I tried to copy the method into one of the classes that extends Routine, but this does not work, or the same problem occurs. Static requirements are especially complex when running () and act () that contain this. and are initializers. I can only make the update () method, as it is, in a routine where I initialize the droid and the panel on which it will act, but I do not see this at all as a solution that I would like to have.

+5
source share
1 answer

Of course, you can refer to an abstract class and call it abstract classes, but the object you specify must be an extender of the abstract class.

For example, create a list of different objects, all expanding on one abstract class.

 public abstract class ExAbstract { public abstract void abstractmethod() {...} } public class ExampleA extends ExAbstract { @Override... } public class ExampleB extends ExAbstract { @Override... } ... List<ExAbstract> list = new ArrayList<>(); list.add(new ExampleA()); list.add(new ExampleB()); ... 

And then you can call it an abstract method.

 for (ExAbstract test : list){ test.abstractmethod(); } 

(or Java 8)

 list.forEach(ExAbstract::abstractmethod); 

But if the object does not expand the facts, and he himself was abstract, he would give an error.

EDIT: in your case with the Routine class, you must create a constructor for it, and then create a new object. (I see that you already have a constructor ...) If you want to use the method without creating an object, use static

In Routine.java:

 public Routine(ExampleArg a){ this.a = a; } 

In your normal call:

 Routine r = new Routine(a); r.start(); 
+1
source

Source: https://habr.com/ru/post/1244110/


All Articles