I'm coming from C++ and I'm trying to inherit the Generic parameter type in Java. Basically, I'm trying to emulate the below C++ pattern:
In C++, I can do:
#include <iostream>
class Node
{
Node* next;
};
class BaseVisitor
{
public:
BaseVisitor(Node* ptr)
{
std::cout<<ptr<<"\n\n";
delete ptr;
}
~BaseVisitor() {};
protected:
virtual Node* Generate() = 0;
};
class DynamicVisitor : public BaseVisitor
{
public:
DynamicVisitor(Node* ptr) : BaseVisitor(ptr) {}
protected:
virtual Node* Generate()
{
std::cout<<"Dynamic Visitor\n";
return new Node();
}
};
class StaticVisitor : public BaseVisitor
{
public:
StaticVisitor(Node* ptr) : BaseVisitor(ptr) {}
protected:
virtual Node* Generate()
{
std::cout<<"Static Visitor\n";
return NULL;
}
};
template<typename T>
class TestVisitor : public T //THIS is where the magic happens..
{
public:
TestVisitor() : T(this->Generate()) {} //allows me to call "Generate".
};
int main()
{
TestVisitor<DynamicVisitor> foo = TestVisitor<DynamicVisitor>();
TestVisitor<StaticVisitor> bar = TestVisitor<StaticVisitor>();
}
Output:
Dynamic Visitor
0x605ed0
Static Visitor
NULL
How can I do the same thing in Java? I tried:
public class Node {
Node next;
}
public abstract class BaseVisitor {
public BaseVisitor(Node n) {System.out.println(n);}
protected abstract Node generate();
}
public class DynamicVisitor extends BaseVisitor {
public DynamicVisitor(Node n) {
super(n);
}
@Override
protected Node generate() {
return new Node();
}
}
public class StaticVisitor extends BaseVisitor {
public StaticVisitor(Node n) {
super(n);
}
@Override
protected Node generate() {
return null;
}
}
public class TestVisitor<T extends BaseVisitor> extends T { //error.. Cannot extend "T".. No magic happens..
public TestVisitor() {
super(this.generate()); //cannot call generate()..
}
}
What is this pattern called? I call it "Base Factory" pattern but I'm not sure the real name for it so I wasn't sure what to search for..
How can I do the same thing as in C++, in Java? Is there "any way" to do the same pattern in Java?