Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic inheritance in java

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.

like image 942
monoceres Avatar asked Oct 10 '10 13:10

monoceres


1 Answers

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.

like image 56
Ezku Avatar answered Sep 19 '22 16:09

Ezku