In c++ we can write:
#include <iostream>
class Base1
{
public: void test() { std::cout << "Base 1" << std::endl; }
};
class Base2
{
public: void test() { std::cout << "Base 2" << std::endl; }
};
template<class T>
class Derived: public T
{
};
int main()
{
Derived<Base1> d1;
Derived<Base2> d2;
d1.test();
d2.test();
}
To get templated inheritance.
Can the same be done in java using generics?
Thanks.
Edit: Adding more info about my intentions
In my scenario I have two subclasses, Sprite and AnimatedSprite (which is a subclass of Sprite). The next step is a PhysicalSprite that adds physics to the sprites, but I want it to be able to inherit from both Sprite and AnimatedSprite.
No. C++'s templates are much stronger than Java's generics. Generics in Java are only for ensuring proper typing during compile time and are not present in the generated bytecode - this is called type erasure.
In my scenario I have two subclasses, Sprite and AnimatedSprite (which is a subclass of Sprite). The next step is a PhysicalSprite that adds physics to the sprites, but I want it to be able to inherit from both Sprite and AnimatedSprite.
Inheritance is not the only form of code reuse. This use case can be handled with other patterns as well, such as simple decoration. Consider something akin to the following:
interface Sprite { ... }
class StaticSprite implements Sprite { ... }
class AnimatedSprite implements Sprite { ... }
class PhysicalSprite implements Sprite, Physics {
PhysicalSprite(Sprite inner) { ... }
...
}
PhysicalSprite would in this case delegate the Sprite parts to some Sprite instance provided in the constructor. It would then be free to add its own handling for the Physics part.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With