Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java class as variable

I am developing a game in Java, and I am trying to create enemies that can shoot projectiles. I am defining the base class for all enemy types, and I have already defined a projectile class. What I would like to do is define a class type variable in the base enemy class, and a shootProjectile() method that will create a new instance of the defined projectile class when called. Pseudo code:

public class EnemyClass extends GameCharacter {
        protected Class projectileType;
        protected int a;
        protected int b;

        // Constructor and other stuff here

        public void shootProjectile() {
            projectileType newProjectile = new projectileType(a, b);
        }
}

public class MyEnemySubClass extends EnemyClass {
        public MyEnemySubClass() {
            super();
            projectileType = MySuperProjectile;
        }
        // Rest of class stuff here
}

public class MySuperProjectile extends Projectile {
        public MySuperProjectile(parameter a, parameter b) {
              // Constructor stuff using a and b
        }
        // Other projectile-related stuff
}

The idea of course is that in the enemy sub classes all I need to do is define what class of projectile they shoot, and the shootProjectile() method in the base class will do the rest.

I'm not sure how to achieve this. I have looked at defining generics but not sure how to make this work for my purposes and I'm not sure I fully understand how they work. Is something like this even possible in Java, or would I need to override shootProjectile for each subclass of EnemyClass to create their own projectile while attacking?

Thanks in advance!

like image 931
Neoptolemus Avatar asked Oct 19 '25 09:10

Neoptolemus


1 Answers

If I understand you correctly, you do not need to use generics.

If you want different implementations of Enemy shoot different implementation of Projectile then just define abstract method Projectile shootProjectile() in Enemy abstract class and implement it as you see fit in each Enemy subclass.

But if you for some reason insist on using them. Them add parameter T to Enemy class. And define the method as T shootProjectile(). Example:

abstract class Enemy<T extends Projectile> {
     abstract T shootProjectile();
}

And again. Do implementation in subclasses like:

class Sniper extends Enemy<SniperRifleBullet>{

    @Override
    SniperRifleBullet shootProjectile() {
        return new SniperRifleBullet();
    }
}

class Projectile{}

class SniperRifleBullet extends Projectile{}
like image 183
ps-aux Avatar answered Oct 21 '25 22:10

ps-aux



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!