Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use generics in builder pattern

Tags:

java

generics

I am trying to use the builder pattern with generics but I don't know how to put it together. I would need some help and an explanation of the correct syntax. My code, and what I have tried.

public class LanguageMatcher<T, S> {

    // Code
    public final static class Builder<T, S> {

        // Code
    }
}

Usage (Error):

new LanguageMatcher<MyClass, YourClass>().Builder<MyClass, YourClass>()....
like image 494
LuckyLuke Avatar asked May 10 '13 19:05

LuckyLuke


People also ask

How are generics used in collections?

The generic collections are introduced in Java 5 Version. The generic collections disable the type-casting and there is no use of type-casting when it is used in generics. The generic collections are type-safe and checked at compile-time. These generic collections allow the datatypes to pass as parameters to classes.

Can I use polymorphism in generics?

The polymorphism applies only to the 'base' type (type of the collection class) and NOT to the generics type.

CAN interface have generics?

Generic interfaces can inherit from non-generic interfaces if the generic interface is covariant, which means it only uses its type parameter as a return value.

What is generics explain with an example?

Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types.


1 Answers

Type parameters are not inherited from outer class to static nested class. So Builder<T, S> actually has a different T and S than LanguageMatcher.

So you don't need type parameters when attempting to qualify Builder with LanguageMatcher. And because the Builder class is static, you don't need an instance of LanguageMatcher to instantiate a Builder:

LanguageMatcher.Builder<MyClass, YourClass> lm =
    new LanguageMatcher.Builder<MyClass, YourClass>();
like image 72
rgettman Avatar answered Sep 23 '22 04:09

rgettman