How can I name a method of an object of type type?

The following is the error code:

SceneNode.java:17: cannot find symbol symbol : method execute() location: class java.lang.Object operation.execute(); ^ 1 error 

the code:

 import java.util.LinkedList; import java.util.Iterator; public class SceneNode<T>{ T operation; public SceneNode() { } public SceneNode(T operation) { this.operation = operation; } public void setOperation(T operation) { this.operation = operation; } public void doOperation() { operation.execute(); } } 

This is a reduction (for your readability) to the beginning of a simple scene graphic. node can be a model, transformation, switch, etc., so I made a variable called operation , the type of which is determined by the variables of class T That way, I can pass the Transformation / Model / Switch object (which has the execute method) and pass it like this:

 SceneNode<Transformation> = new SceneNode<Transformation>(myTransformation); 

I am sure that the base class SceneNode and subclasses for all types of nodes would be better (I tested generics, only found out about them recently). Why is this not working? I have to miss something fundamental in relation to generics.

+7
source share
3 answers

This does not work, because T can be of any type, and Java is statically typed. The compiler does not know if you are trying to create a SceneNode<String> - what would execute do?

One option is to create an appropriate interface, for example

 public interface Executable { void execute(); } 

and then restrict T to SceneNode to implement Executable :

 public class SceneNode<T extends Executable> { ... } 

(I find it a little strange that T should extend Executable , and not implement it in the source code, but then T may turn out to be the interface itself, so I think it makes sense.)

Then it should work fine. Of course, you could make Executable abstract superclass - or even a (not finite) concrete class - if you want, but I usually prefer to use an interface if I had no reason to.

+8
source

I assume you came from C ++ background.

The compiler has no idea what the T thing might be, because you didn't say that.

If you had an interface called, for example, Executable , that defines your execute() method, you would need to do:

 public class SceneNode<T extends Executable> { // ... } 

Now the compiler will know that T is Executable and will give you access to all methods in this interface.

+8
source

Java is a statically typed language. You must know the type at compile time in order to be able to call the method. Instead of a subclass, you can have an Executable interface that defines the execute() method. T (without any <T extends SomeClass> ) has only the methods defined by java.lang.Object .

+1
source

All Articles