Home > Net >  How to use subclasses of an abstract class in a normal class
How to use subclasses of an abstract class in a normal class

Time:04-26

I would like to ask a question about Abstract Classes in Java.

I have a class named as Car. Also, I have created an Abstract class named as State. This abstract class has four subsclasses named are, GotoXY,Rest,Shake and Chase respectively.

A Car has a state and its state is changing randomly.
In the Car class I have created a variable as

private State state;

First Question : Should I create a constructor with State parameter in the Car Class? Like:

Car(State _state){.//.}

State Class :

public abstract class State {

   public State chooseRandomState() {          
      return new GotoXY();
   }
   private void pickAnotherState(){
      //Random rnd = new Random();
      //currentState = States.values()[(int)(Math.random()*States.values().length)];
      //System.out.println(currentState);

   }

   public abstract String getCurrentStateName();
}

Car Class is a normal class.

I have instantiated the Car class in a Common Class.

Second Question: Should I create an enum in the State class and choose a random state? How should I handle the Random state changes in the Car Class?

CodePudding user response:

First question: Yes, you should code a constructor that receives any parameters needed to properly initialize the object's state (in this case, a State instance).

Second question: No, I wouldn't recommend an enum here. Look: Enums are aimed to produce a closed, finite number of objects known at compile-time. Interfaces, instead, may be extended by a number of implementations, not necessarily known at compile-time (at least, this was the original interface paradigm, before Java 15 introduced sealing).

I suggest you should keep your Car class absolutely independent of which and how many State implementations exist. How? Well, any random choice is based upon a numeric value (from 0 to 1) produced by java.lang.math.Random. So, you could instantiate every existing State implementation and store them into a List collection, and make Car index this list upon a random number (in the fashion your pickAnotherState method's commented code does it).

And, to keep Car and State instances completely independent, you'd better code a new class StateManager that contains static methods to create this list of States and publish it through a public getter for the Car class to use it. In this way, whenever you code a new implementation of State, it will affect only the StateManager, not the client classes (like Car).

  •  Tags:  
  • java
  • Related