Note that there are some explanatory texts on larger screens.

plurals
  1. POCan I pass object from subclass to abstract class?
    text
    copied!<p>This is my abstract class AbstractVehicles which implements Vehicles interface</p> <pre><code>public abstract class AbstractVehicles implements Vehicles{ } </code></pre> <p>and here's my CarImpl</p> <pre><code>public class CarImpl extends AbstractVehicles implements Car { private CarAI ai; private static final int CAR_FUEL_LEFT = 10; public CarImpl(){ super(FUEL_LEFT); this.ai = new CarAI(); } public void move(World w){ // AI is using here ai.act(w); } } </code></pre> <p>and here's my BicycleImpl</p> <pre><code>public class BicycleImpl extends AbstractVehicles implements Bicycle { private BicycleAI ai; private static final int BICYCLE_FUEL_LEFT = 10; public BicycleImpl(){ super(BICYCLE_FUEL_LEFT); this.ai = new BicycleAI(); } public void move(World w){ // AI is using here ai.act(w); } } </code></pre> <p>where interface of Car and Bicycle are marker Interface that</p> <pre><code>public interface Car extends Vehicles { } public interface Bicycle extends Vehicles { } </code></pre> <p>The question come here I have implemented an AI for car and Bicycle individually in other packages called BicycleAI and CarAI. But there code in their CarImpl and BicycleImpl are the same. So I would Like to add that into the abstract class, so that code can be reused. And class BicycleAI and class CarAI is implementing interface AI. </p> <p>As we can see above, their code for act is the same, but there AI objects are different. Is there anyway I can put this code into the abstract class?</p> <p>I tried to do this </p> <pre><code>public abstract class AbstractVehicles implements Vehicles{ protected AI ai; private int fuelLeft; public AbstractVehicles(int fuelLeft){ this.fuleLeft = fuelLeft AI ai = new AI(); } public void move(World w){ ai.act(w); // But I have no idea this is CarAI or BicycleAI } } </code></pre> <p>I am a bit confused about the constructor in AbstractVehicles and constructor in RabbitImpl. If I create an object RabbitImpl, and I call the move. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload