Elegant way to create one of a large number of classes - java

For context, I'm trying to make a game something along the lines of Pokemon. You obtain, train and fight monsters.
Each species of monster is a class inheriting from an abstract base class (so they can have unique behaviour), and hopefully there will be a very large number of different species throughout the game. Ex:
abstract class Monster {
int hp;
void attack();
//Etc.
}
public class FireBreathingDragon extends Monster {
static String species_name = "Fire Breathing Dragon";
//Blah
}
So when the player is exploring, they will encounter monsters local to an area at random. The game then needs to create a monster at random from a list of species that live in that area. Now to make this code reusable between areas (and make it easy to create monsters dynamically in other places in the code) I don't want to hardcode the possibilities into the area. Instead I think I'd like something along the lines of a factory that creates a monster of a given species on demand, something like:
public class MonsterFactory {
Monster createMonster(
String species_name,
//Possibly other paramters
);
}
The problem is then implementing createMonster in a "nice" or "elegant" way when you have (potentially) tens or hundreds of different Monster classes. Of course you could use a very very long if-else if-else or switch statement, but that's horrible to write and extend. Is there a nice way to do this? It would also be good if it was relatively easy to extend when adding more monsters.
Or is there some totally different design I should be using instead?
Disclaimer: My java is a little rusty, syntax may not be perfect, sorry about that.

You could register all your Monster implementation classes in a List.
List<Class<? extends Monster>> monsterTypes = new LinkedList<>();
monsterTypes.add(FireBreathingDragon.class);
// more
This doesn't have to be hardcoded. You can externalize it to some XML, Json, or other file format.
The factory instance or class can then choose a monster type from the list at a random index. You can then use reflection to instantiate the type.

The simplest solution is to have a data driven monster class. This means you only have one class (or a small number) and this class can be used for a wide variety of monsters with different attributes and abilities.
You could have a CSV file which contains each species and all the attributes and abilities fr that species. This way you could add a species by adding a line in a spreadsheet.

This solution uses Class Factories without any form of reflection. Why is this important in the context of the question ("the most elegant way")? From a very interesting exchange with another contributor: I quote Sun/Oracle's Reflection API Tutorial "Reflection is powerful, but should not be used indiscriminately. If it is possible to perform an operation without using reflection, then it is preferable to avoid using it." To justify this, Sun/Oracle's authors resort to extremely technical reasons internal to Java. I agree with them, but my main reason is long-term code maintenance and tooling. And what's the main alternative to reflection? Annotation-based automatic code generation. I can't do something like that in this short space, but I can produce what should be, more or less, the resulting code:
public interface Factory<T> {
T make();
}
public static class BasicMonster {
}
public static class Monster1 extends BasicMonster {
public static final Factory<Monster1> getFactory() {
return new Factory<Monster1>() {
public Monster1 make() { return new Monster1() ; }
};
}
}
public static class Monster2 extends BasicMonster {
public static final Factory<Monster2> getFactory() {
return new Factory<Monster2>() {
public Monster2 make() { return new Monster2() ; }
};
}
}
List<Factory<? extends BasicMonster>> monsterFactories= new ArrayList<Factory<? extends BasicMonster>>();
{
monsterFactories.add(Monster1.getFactory());
monsterFactories.add(Monster2.getFactory());
}
...
BasicMonster newMonster= monsterFactories.get(aRandomOne).make() ;
Form static class used to indicate classes not intended as inner.
Even if list monsterFactories were initialized through reflection, the presence of factory objects in the code permits a higher level of static analysis than reflective constructor invocation.

You could put all the classes in a specific package, then scan that directory for class files, load them, and track the ones that extend Monster. You could even define some custom annotations to help manage this, e.g. #IgnoreMonster to temporarily disable some without having to change the location of the file. This is similar to the way e.g. Hibernate scans source to find entity mappings.
Here is an example. All the Monster classes are placed in package dload.monsters. First, here's the base class I'm using for this example:
package dload.monsters;
public abstract class Monster {
public abstract String getName ();
}
Then, a MonsterFactory which scans for all classes in the dload.monsters package (sorry its a little sloppy, and I skimped out on exception handling):
package dload.monsters;
import java.io.*;
import java.net.*;
import java.util.*;
public class MonsterFactory {
private static final List<Class<? extends Monster>> monsterClasses = new ArrayList<Class<? extends Monster>>();
private static final Random random = new Random();
#SuppressWarnings("unchecked") // <- for monsterClasses.add((Class<? extends Monster>)cls);
public static void loadMonsters () throws Exception {
// in this example, Monster is in the same package as the monsters. if
// that is not the case, replace "." with path relative to Monster.
File folder = new File(Monster.class.getResource(".").toURI());
for (File f : folder.listFiles()) {
if (f.getName().endsWith(".class")) {
String name = f.getName().split("\\.")[0];
// replace "dload.monsters." below with package monsters are in
Class<?> cls = ClassLoader.getSystemClassLoader().loadClass("dload.monsters." + name);
// if Monster is not in same package as monsters, you can remove
// cls.equals(Monster.class) check. this check makes sure the loaded
// class extends Monster, but is not the Monster class itself (since
// its also in that package).
if (Monster.class.isAssignableFrom(cls) && !cls.equals(Monster.class)) {
System.out.println("Found " + cls.getSimpleName());
monsterClasses.add((Class<? extends Monster>)cls);
}
}
}
// at this point all Class's for monsters are in monsterClasses list.
}
public static Monster randomMonster () throws Exception {
// choose a class at random
int n = random.nextInt(monsterClasses.size());
Class<? extends Monster> cls = monsterClasses.get(n);
// instantiate it
return cls.newInstance();
}
}
Then, when you want to use it:
public static void main (String[] args) throws Exception {
// load monsters; only need to do this once at startup
MonsterFactory.loadMonsters();
// create 10 random monsters
for (int n = 0; n < 10; ++ n) {
Monster m = MonsterFactory.randomMonster();
System.out.println("name is " + m.getName());
}
}
Note that at any time you can check the monster's Class for relevant annotations.
Another option, if the classes are already loaded (which they won't be if they've never been used or explicitly loaded) is to use Instrumentation.getAllLoadedClasses() to get a list of all classes currently loaded, then scan through all classes looking for ones that are assignable to a Monster.
Note: I do feel like there is a cleaner way to do the actual scan, and I haven't tested this in a JAR. Suggestions welcome.
All that being said, if a Monster's behavior could be entirely defined by data, I also support and recommend the data driven approach described above.

You should take a look at the Cartesian Product Algorithm. It will generate every combination of products and you can then choose one at random.
Essentially the algorithm will take arrays of attributes and create unique combinations of the different attributes and add them to an array. You can then randomly select a key from the array when you create the enemy. That way every enemy has a random chance to have any number of attributes.

have an interface or base class that provides a monster.
I thought I'd include this wiki-bit, "The factory method pattern is an object-oriented creational design pattern to implement the concept of factories and deals with the problem of creating objects (products) without specifying the exact class of object that will be created."
This lets you use superclass methods or interfaces exclusively without ever needing to know the specific subtype of the interface. This is important because you cannot call new base_monster();
abstract class base_monster {
abstract base_monster factory();
}
/// make sure every monster has a name...
//
abstract class Monster extends base_monster {
String name;
static int object_counter = 0;
Monster factory() {
name = Integer(object_counter).toString();
object_counter();
return this;
}
/// this class has a useful setter
void object_counter( int c ) { object_counter++; out.println( object_counter ); }
}
class Griffon extends Monster {
Monster factory() { return new Griffon(); }
}
class Harpy extends Monster {
Harpy() { name = "Grizelda WhuttleThut III"; }
Harpy factory() { return new Harpy(); }
}
class BlackHarpy extends Harpy {
BlackHarpy factory() { super.factory(); return new BlackHarpy(); }
}
// we assume that each class has a default constructor. But,
// if the array is filled with monsters of different subclasses we
// would have to use reflection or nasty instanceof switches to be
// able to call a (specific) defined constructor.
ArrayList<Monster> monsters = new ArrayList<Monster>();
monsters.add( new BlackHarpy() );
for( int I = 0; I < ave_monsters_appearing; I++ )
monsters.add( new Harpy() );
//
// an array of ten harpies and a boss Harpy.
///
// how can this array of monsters be copied into the other array?
// (we want object copies, not reference copies)
///
ArrayList<Monster> local_monsters = new ArrayList<Monster>();
/// solution: use the factory method
for( Monster m : monsters )
local_monsters.add( m.factory() );
.
.
Hope this solves the problem of not having a static method.

Related

Why is the compiler allowing the variable of class "I" to be assigned an object of class "N" which inherits the "I" class

class I {
String s="yes its me:I";
void Mine(){
System.out.println(s);
}
}
class N extends I {
String l="yes its me:N";
void Mine(){
System.out.println(l);
}
}
class T extends N{
String m="yes its me:T";
void Mine(){
System.out.println(m);
}
}
class Test{
public static void main(String[] args) {
I i=new I();
N n=new N();
T t=new T();
I r; // r is a variable of class type I
r=i; // fine here
r.Mine(); //no doubt here
r=n; // heres the problem
r.Mine(); // these are working only
r=t; //with overriding methods existing & no other method exists in all classes
r.Mine();
}
}
Also tell me please: if we declare a variable of class type, what does it do (I mean is it going to recognise by the number of methods and instance variables of the class or only methods or only instance variables).
class Vehicle {
Engine myEngine = new Engine();
void start() {
myEngine.start();
}
void stop() {
myEngine.stop();
}
}
class VehicleWithSteering extends Vehicle {
Steering mySteering = new Steering();
void start() {
mySteering.reset();
myEngine.start();
}
void steerLeft() {
mySteering.left();
}
void steerRight() {
mySteering.right();
}
}
As you can see, VehicleWithSteering does have methods which the basic Vehicle did not have. It also overrides the void start() method as starting this more complex vehicle involves a different routine.
class NoviceDriver {
Vehicle myVehicle;
public NoviceDriver(Vehicle vehicle) {
myVehicle = vehicle;
}
void doSomething() {
myVehicle.start();
myVehicle.stop();
}
}
class AdvancedDriver {
VehicleWithSteering myVehicle;
public NoviceDriver(VehicleWithSteering vehicle) {
myVehicle = vehicle;
}
void doSomethingElse() {
myVehicle.start();
myVehicle.steerLeft();
myVehicle.stop();
}
}
The AdvancedDriver needs additional functionalities which the basic Vehicle can not satisfy, so it will always need an instance of VehicleWithSteering.
class Test{
public static void main(String[] args) {
// Create one basic vehicle
Vehicle a = new Vehicle();
// And one more advanced
VehicleWithSteering b = new VehicleWithSteering();
// A novice driver is satisfied with having a basic vehicle
NoviceDriver x = new NoviceDriver(a);
// The advanced driver however needs more functionality
AdvancedDriver y = new AdvancedDriver(b);
// A novice driver can use the advanced vehicle as well
// But he will not bother about the advanced functionality
NoviceDriver z = new NoviceDriver(b);
}
}
The NoviceDriver only knows how to access methods of Vehicle. But since these methods are also present in VehicleWithSteering, he can use that one as well. NoviceDriver doesn't even know what steering means so he won't touch any controls he doesn't know about.
You can't fit an AdvancedDriver with a Vehicle as this one doesn't incorporate the required steering methods.
If there was an even more advanced refinement of the VehicleWithSteering, both the NoviceDriver and the AdvancedDriver could still use it for executing their limited tasks as it still provides the required basic functionalities.
The NoviceDriver has access to all public methods and properties the original Vehicle had. It does not know about new methods or properties added later on. In this case, it could see the inherited Engine myEngine property on the VehicleWithSteering, but it can not see the new Steering mySteering property.
As for your last question: That depends on the language.
In Java, each class has an internal list of other inherited classes and interfaces it implements. Whenever you are casting a refinement to a more primitive type, Java will check whether the primitive type is in the list or not. This behavior is also used in other strictly typed languages such as C++, C# and many others.
The alternative concept would be Duck-Typing.
When I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck.
When a language uses Duck-Typing, it will look up the requested method in the object by name and signature. This may happen either at compile time or at runtime, in latter case an exception is thrown in most languages supporting Duck-Typing.
Some languages such as PHP and various other scripting languages feature both strict type checks and Duck-Typing. That means you can both optionally enforce a strict type check on the list of inherited classes and implemented interfaces, as well as defaulting to Duck-Typing when that check was omitted.
Consider:
class MP3Player // any MP3 player
class IPod extends MP3Player // an iPod MP3 player
class IPodClassic extends IPod // an iPod Classic in particular
Then:
MP3Player m = new IPod();
m.playMp3();
is allowed because an iPod is an MP3 player and can do anything an MP3 player can do.
IPod i = new MP3Player(); // Not allowed
i.showAppStore(); // MP3Player might not have app store
is not allowed because not all MP3 player's are iPods.
IPodClassic ic = new IPod(); // Not allowed
ic.getHardDisk(); // Not all iPod objects have a hard disk.
is not allowed because not all iPod's are iPod classics.

How to Prevent instantiation of concrete classes?

Lets say I have a Record Interface and I can have N number of its concrete implementation classes eg. PropertyRecords,LoanRecords etc.How do I ensure there is no object of these N classes is created by client using new keyword?
Its quite easy if I have a single subclass;I can Make all the constructors package private;so that I can write a Factory class in the same package which will have a method which will be responsible for creating instances.But how to create a virtual Factory able to create several implementations of a single interface or abstract class.
Hope i am able to put myself correctly.Please ask if any clarification needed.
Thank you.
Not sure why you would want this, but your Factory class can use reflection to create instances like this:
public class RecordFactory {
public Record newInstance(Class<? extends Record> klass, Object... args) {
Constructor[] ctors = klass.getDeclaredConstructors();
// find the right constructor here..
return ctor.newInstance(args);
}
}
Then your clients can create instances like:
RecordFactory.newInstance(Loan.class, ...);
I'm not entirely sure I understand what you're trying to achieve (comment on this is not), but here are my thoughts:
Sounds like what you really want is to implement the Flyweight design pattern (http://en.wikipedia.org/wiki/Flyweight_pattern).
If you really want to implement this as you describe it (again, under the assumption that I understood correctly), the following should work:
public class Record {
private static final int MAX_INSTANCES = 20;
private static volatile int instanceCounter = 0;
private Record() {
if (instanceCounter >= MAX_INSTANCES)
throw new RuntimeException("max instances exceeded");
instanceCounter ++;
}
}

execute code in java fields

I'm in a position where I have referenced a static field variable to a custom class. I need to make alterations to the variable with methods from the class it references. I can not instantiate the class under construction. Simplified example:
public class House {
private static MaterialsRequired matsReq = new MaterialsRequired();
private String size;
private House(String size) {
this.size = size;
}
public static MaterialsRequired getMaterialsRequired() {
}
public static void Build(String size) {
new House(size); //Do I need to put 'this(size)' here?
//some code here to expend the materials required factored based on size.
}
To construct the house I need to know the materials required (for standard size). To know the materials required I need to call the addMaterial() method of MaterialsRequired. What do I do?
EDIT: I need to call the addMaterial() method repeatedly on matsReq. Maybe ten times. When I call House.build() I want the matsReq to have been altered by method calls (if my question was unspecific). Also it doesn't satisfy me to just set the materials required every time the build() or getMaterialsRequired() methods are called.
The question have been answered! Solution:
private static MaterialsRequired matsReq = new MaterialsRequired();
static {
matsReq.addMaterial(mat1);
matsReq.addMaterial(mat2);
matsReq.addMaterial(mat3);
}
private String size;
Having a build method doesn't work, because it is just another constructor. It's what happens when you make an instance. I'm guessing, if anything, you build to be outside of the class. It would be something that called the constructor and did a couple other things.
What you probably want is, outside of the class, a method that creates an instance of a house (using the constructor) and then some code to "use up" the materials needed to make the house from a structure that holds the materials (again, outside of the class).
Since you seem to want to make houses with different material requirements, why don't you make subclasses of the most basic house (or better yet, an abstract class, maybe called "dwelling") that have a different required materials list.
Doing some guesswork...
public class StandardHouse{
public static MaterialsList MATERIALS_REQUIRED = new MaterialsList();
MATERIALS_REQUIRED.add("material", numMats);
...
public StandardHouse() {
//probably don't need anything here
}
}
Then later
MaterialsList matsYouHave = ...;
StandardHouse house1 = new StandardHouse();
matsYouHave.remove(StandardHouse.MATERIALS_REQUIRED);
Try making them in two classes
public class House {
private List<String> materialList = new ArrayList<String>();
private House(List<String> materialList ) {
this.materialList = materialList ;
}
public void Build() {
MaterialsRequired matsReq = new MaterialsRequired();
materialList .add(matsReq.setMaterialsRequired("material1"));
materialList .add(matsReq.setMaterialsRequired("material2"));
materialList .add(matsReq.setMaterialsRequired("material3"));
//some code here to expend the materials required factored based on size.
}
And then
class MaterialRequired
{
private String materialsRequired;
public String setMaterialsRequired(String material) {
materialRequired = material;
return materialRequired;
}

Where to put a interface related variable that it is not static and final

I am in a very early stage of game development. It is some sort of turn based game like Warhammer or Warcraft. Some creatures can regenerate the damage they have suffered and to represent this I have a interface like this
public interface Regenerative {
void regenerates();
}
So a creature that regenerates is
public class SomeMonster() extends BaseCreature implements Regeneative{
//Code
private int hitPoints;
public void regenerates(){
hitPoints = hitPoints + regenerateValue;
}
}
The problem I face is that not all the creatures regenerates the same ammount of hit points so I have to place that amount (regenerateValue) somewhere. Since I cannot put it on the interface (because I don't want the ammount to be the same to all the creatures) I have thought in adding a new property to the creature class
public class SomeMonster() extends BaseCreature implements Regeneative{
//Code
private int regenerateValue;
public void regenerates(){
hitPoints = hitPoints + regenerateValue;
}
}
but I don't like it this way (why a creature that doesn't regenerate should have a regenerateValue of 0?). I think it is giving a class unnecesary properties and thus a bad design. What do you think is the best approach for this case?
The problem I face is that not all the creatures regenerates the same ammount of hit points so I have to place that amount (regenerateValue) somewhere.
Why does it have to be a field anywhere? Some implementations of the interface might use a different value per instance; others might use a constant value.
This is an implementation detail - and thus inappropriate for the interface. You could potentially put it in an abstract superclass which implements the interface, of course.
Code which knows about the interface almost certainly shouldn't know or care the details of how much a creature regenerates - maybe they regenerate in terms of magic rather than just hit points, for example, or maybe the level of regeneration depends on some other function of their state. Callers shouldn't care.
I would add it to the abstract BaseCreature and not worry about it too much. Your BaseCreature may end up with lots of properties which are effectively "turned off" but the alternative is to create a complex inheritance tree. As Java doesn't support multiple inheritance this will frustrate your ability to abstract all the combinations you might like away.
The solution i use may be a bit over-ingeniered, but this allow for a lot of extension (regeneration, poison, protection...)
I use of interface "CreatureProperties" that define a integer value along with an id, and can perform action on a monster at each turn. You subclass those properties to perform a given property
abstract class CreatureProperties {
protected String id = "";
protectd int propertyValue = 0;
public void actOn(BaseMonster);
// plus setter and getter
}
public RegenerationProperty implements CreatureProperties {
final public REGENERATION_ID = "Regeneration";
int regenerationValue = 0;
public RegenerationProperty(int value){
id = REGENERATION_ID;
propertyValue= value;
}
public void actOn(BaseMonster monster){
monster.setHitPoint(monster.getHitPoints()+propertyValue);
}
}
in the BaseMonster class, you manage a set of MonsterProperty, initially empty.
class BaseMonster {
protected List<CreatureProperties> properties =
new ArrayList<CreatureProperties>();
// plus management of propeties : add remove, iterator...
public void update(){
// perform all properties-linked update to monster
foreach (CreatureProperty property : properties){
property.actOn(this);
}
}
}
in the subclass for SomeMonster, you simply add during instanciation the set of properties for this type of monster.
class SomeMonster extends BaseMonster {
public SomeMonster(){
properties.add(new RegenerationProperty(5)); // presto : monster regenerate
}
}
I'm using the Id in some case where the property is not used each tick (ie nothing in the update), but for example damage reduction (id="LightningReduction"), or to modify the list of existing properties (a property that remove all regenerationProperty and add PoisonProperty of same value...).
I think your design is probably ok, as you would only need to include a regenerateValue in the classes that implement the Regenerative interface. So there would be no need to include a regenerateValue.
Otherwise you could look at more complex design patterns that favor composition over inheritance. This way you could cater for the possibility of dynamically adding Regenerative abilities to a monster along with other 'abilities' during the game, rather than having to recompile the game each time you need to make change the behaviour of your monster.
What if all monster regenerate, but some of them with 0 regenerate value (the same as not regenerating)?
So you don't need the inferface:
public class SomeMonster() extends BaseCreature {
//Code
protected int regenerateValue; //protected, so that subclasses can override the value
public void regenerates(){
hitPoints = hitPoints + regenerateValue;
}
}
The regenerateValue starts with 0, so you have to override the value in subclasses that want to actually regenerate
Edited to remove the " implements Regeneative"
You could add a method in your interface, like getRegnerationValue(), making sure all creatures with that interface have this method that holds the value or formula if that is something you would like to work with.
The question you should ask yourself is this: if a creature should regenerate, how do you know that? Will it implement a different (or extending) base class? one that implements Regenerative?
If the answer is that you will extend the base class (to something like BaseRegeneratingCreature) and all regenerating creatures will extend that class, then this is your answer: BaseRegeneratingCreature should implement that interface, and have all properties required for regenerating.
All non-regenerating creatures should directly extend BaseCreature (or another extending class), and will not need the regeneration related properties.
Then, your base class could have some method like:
OnStartOfTurn();
which will, in BaseRegeneratingCreature, call regenerates() (and then probably call super()), and in BaseCreature do something else or call other methods.

How can I have two classes share the same variable definitions

What I really need is to be able to declare regular variables in an interface and implement that interface in two classes that I would not have to have to re-declare these in each class (ie class.data.variables instead of class.variables). Is there any way that I could achieve the same goal differently?
To give more detail. Essentially, I have created a small drawing program that drops JLabels on a JPanel that is on a JScrollPane. Because I have a specific design for these JLabels (ie they are not just for drawing they represent airline objects for this application), I have a class that extends JLabel and adds my application specific variables to it. Ultimately, I read and write an XML file with these variables so they can load and save their designs. Since I can not use this extended class for my XML definitions because it screams about the parent class even though I told it to have NONE as the accessor (I read there is a bug), I have to create an identical class and copy values back and forth for saving and loading. Not too much of a problem except when I add a variable to the JLabel extended class and forget to add it to the XML mimic class and subsequent copy routines.
So, it would be great if I could make one class (say CellDataRecord.java) that held the extra data declarations and have that class be used in both places (the JLabel extension and the XML data) without having to have something like XML.data.CellDataRecordXXX.
You can do that with inheritance or using an interface, where the variable is set as a constant in the parent class. Since you are extending a JLabel, you should implement the interface on both classes:
public interface MyInterface {
int someint = 9;
}
public class MyClass1 extends JLabel implements MyInterface {
//this class has access to `someint`
}
public class MyClass2 extends JLabel implements MyInterface {
// also has access to `someint`
}
Edit
Since you want to be able to change the same variable from different classes, you have to ensure you aren't changing copies and are changing the same variable, so you should use a volatile keyword on the variable to indicate to java that all threads should check the value before it updates it.
Now you'll need to have a separate class so that instances can be made from other classes to get the value. You have to use the static keyword to ensure that one copy is kept for all class instances.
public class MyVariableWrapper {
public static volatile int some_var = 9;
public void updateSomeVar(int newvar) {
some_var = newvar;
}
public int getSomeVar() { return some_var; }
}
Now the other two classes just do this:
public class MyClass1 extends JLabel {
MyVariableWrapper myVariableWrapper;
MyClass1() {
super();
myVariableWrapper = new MyVariableWrapper();
// now I have access to `some_var`
}
}
public class MyClass2 extends JLabel {
MyVariableWrapper myVariableWrapper;
MyClass2() {
super();
myVariableWrapper = new MyVariableWrapper();
// now I have access to the same `some_var` as MyClass1
}
// this is a wrapper method for your convenience
// since you don't like the excess code when accessing the variable
public int getSomeVar() {
return myVariableWrapper.some_var;
// or myVariableWrapper.getSomeVar();
}
public void setSomeVar(int newvar) {
myVariableWrapper.some_var = newvar;
// or myVariableWrapper.setSomeVar(newvar);
}
}
Now you can do this:
MyClass2 myClass2 = new MyClass2();
System.out.println(""+myClass2.getSomeVar());
I'm not sure I 100% grasp your problem but from the first few lines of your description, instead of implementing an interface, you could define an abstract class and have your classes extend it. That way, you'll be able to define attributes in the abstract class and these will be common to all subclasses.

Categories