Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
608 views
in Technique[技术] by (71.8m points)

how to define a variable of a class type in java when the class has extends?

i have this class :

   public class FindPath<T,N extends Path<T,N>> {

    public FindPath() {
        
   // the constructor ...
    }
}

and the path interface:

public interface Path<N, P extends Path<N,P>>
            extends Iterable<N>, Comparable<Path<?,?>>

where T , P and N are generic types. i want to define a variable FindPath in another class , and call it's constructor , basically i want something like this :

public class TestD {

private FindPath <WNode,WNodePath extends Path<WNode,WNodePath>> Find_Path = new FindPath;

} 

( WNode,WNodePath are another classes i use in the generic types )

what am i doing wrong ? how to do this right ?

also another question :|| the WNodePath class is defined like so :

public class WNodePath implements Path<WNode, WNodePath > { .. }

the path interface is Comparable , does that mean that also WNodePath is Comparable , which means that i can use it compareTo() function in a priority queue ?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

When you declare a FindPath reference you don't use extends, that's used to provide bounds (limits) on the classes it is legal to use for that type parameter. (You can use extends when you have a wildcard type parameter, but that's not relevant here, see https://docs.oracle.com/javase/tutorial/extra/generics/wildcards.html)

Just say:

    private FindPath<WNode,WNodePath> findPath = new FindPath<>();

Which compiles.

Yes, WNodePath implements Comparable, transitively via Path.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...