Nominalista
Nominalista

Reputation: 4838

Value in generic class in Java

Is it possible to create class, where e.g. second parameter is value? Constructor would look something like this:

FancyClass<Integer, 1> myFancyClass = new FancyClass<>();

Upvotes: 0

Views: 54

Answers (2)

NonameSL
NonameSL

Reputation: 1475

No. There's no logic in doing so anyway. From wikipedia:

Generics are a facility of generic programming that were added to the Java programming language in 2004 within J2SE 5.0. They allow a type or method to operate on objects of various types while providing compile-time type safety.

A small example:

The class Lunchbox represents a lunch box, which inside of it it's seperated into 2 different containers. Each "container" within the lunchbox can contain a bunch of items, but those items can be only of one (same) type.

Without generics, we would have to predefine 2 types for both sides of the containers. But lets say we wanted to do it so each Lunchbox can have different types of items. That's when we need generics:

public class Lunchbox<V1, V2>

Now inside the LunchBox class (and only inside the LunchBox class) you can access two types: V1 and V2. They're handeled like normal classes.

V1 objectOfTypeV1 = ...; //I can even declare variables with that type.

Now we can create lunchboxes of many kinds:

Lunchbox<String, Integer> lunchbox1 = new Lunchbox<>();//Contains strings and integers
Lunchbox<Foo, Bar> lunchbox2 = new Lunchbox<>();//Contains Foos and Bars
LunchBox<LunchBox<Foo, Bar>, Integer> lunchbox3 = new LunchBox<>(); //Contains lunchboxes (containing Foos and bars) and integers

For your question: If we were to put a value as a generic class, it wouldn't make any sense. Lets continue with the Lunchbox class - How can our lunchbox hold a type 1, when there is no such thing? You can't declare...

1 object = new 1();

That's not a class. That's a value. I don't understand why you'd want to put a value in a generic, and it doesn't make sense. Hope I helped.

Just in case you didn't understand anything from this, here's a link to Oracle where they have a lesson about generics, why to use them: Click here.

Why use generics? -Oracle

Upvotes: 1

Kayaman
Kayaman

Reputation: 73578

No. Generics are for types not for literal values.

I don't know what you're trying to do, but if there's some actual idea behind your code, you could easily implement it with

public class FancyClass<T> {
    T myVal;
    public FancyClass(T val) {
        myVal = val;
    }
}

FancyClass<Integer> myFancyClass = new FancyClass<>(1);

Upvotes: 6

Related Questions