How to create a Java class, similar to a C++ template class?


Question

How do I write an equivalent of this in Java?

// C++ Code

template< class T >
class SomeClass
{
private:
  T data;

public:
  SomeClass()
  {
  }
  void set(T data_)
  {
    data = data_;
  }
};
1
21
6/14/2013 11:28:02 PM

Accepted Answer

class SomeClass<T> {
  private T data;

  public SomeClass() {
  }

  public void set(T data_) {
    data = data_;
  }
}

You probably also want to make the class itself public, but that's pretty much the literal translation into Java.

There are other differences between C++ templates and Java generics, but none of those are issues for your example.

39
12/6/2009 4:20:21 AM

You use "generics" to do this in Java:

public class SomeClass<T> {
  private T data;

  public SomeClass() {
  }

  public void set(T data) {
    this.data = data;
  }
};

Wikipedia has a good description of generics in Java.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon