Skip to main content

Generics parameters should accept interfaces

4 replies [Last post]
cowwoc
Offline
Joined: 2003-08-24
Points: 0

<br />
public interface TreeNode><br />
{<br />
  /**<br />
   * Returns the node's children.<br />
   */<br />
  public Set getChildren();<br />
}<br />

In the above code sniplet I defined a generic representation for a tree node that has children that are also tree nodes. The problem with Generics is that I cannot instantiate a variable of type "TreeNode" because the compiler will complain that the parameter type "is not within its bounds". If I understood this correctly, the parameter I pass in must be a concrete class, not an interface. This is problematic because I want to be able to say:

<br />
  private void doSomething(TreeNode parent)<br />
  {<br />
    for (TreeNode child : parent.getChildren())<br />
    {<br />
      // do something with the child<br />
    }<br />
  }<br />

but I cannot. Why this not allowed?

Gili

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
cowwoc
Offline
Joined: 2003-08-24
Points: 0

I guess my RFE is actually:

We should be able to say:

SomeClass directly instead of

SomeClass

If it works for concrete classes, it should work for interfaces. Did I misunderstand anything?

Gili

tackline
Offline
Joined: 2003-06-19
Points: 0

It's not to do with interfaces vs non-abstract classes. It only really makes a difference for types right of an & in intersection types.

In the example if you needed to write something along the lines of TreeNode, then because TreeNode is a generic type what you actually need is TreeNode> or TreeNode>>, etc.

In the body of the doSomething method the node is only retrieved from, so you can get away with a wildcarded type.

cowwoc
Offline
Joined: 2003-08-24
Points: 0

My mistake. Fixed by replacing

[code]
public Test(TreeNode node)
{
}
[/code]

by

[code]
public Test(TreeNode node)
{
}
[/code]

tackline
Offline
Joined: 2003-06-19
Points: 0

Yup, the compiler is complaining that the second TreeNode in "TreeNode" should have a generic parameter. It can be simplified slightly as extends TreeNode is implicit.

private void doSomething(TreeNode parent) {

For a tree with specific node types, we can use a method with its own generic parameter. This should allow the nodes to be rearranged.

private > void doSomething(N parent) {