tags:

views:

2091

answers:

3

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_;
  }
};
+5  A: 
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.

Laurence Gonsalves
Actually, one difference, which isn't a generic/template thing but a more fundamental difference between C++ and Java, is that the set method in C++ copies the supplied object, while the Java version just copies the reference.
Laurence Gonsalves
Wow, and the cool thing about "generics" is that I can even express something like public class SomeClass<T extends OtherClass>! I dont think that ability is present in C++. So cool!
ShaChris23
ShaChris23: the prevalent idiom in the C++ stdlib is to use duck typing: "if all the attempted uses work with the object, it has the interface expected" (std::reverse_iterator being a good, clear example), and this is similar to Python and [my understanding of] Go. It is still sometimes useful to make those restrictions yourself (or at least people ask for it :P), and you can use boost::enable_if, static asserts (with type traits to detect inheritance in this case), and similar for that. Concepts were supposed to help address this, but that's another story.
Roger Pate
+1  A: 

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.

Moishe
A: 
/**
 * This class is designed to act like C#'s properties.
 */
public class Property<T>
{
  private T value;

  /**
   * By default, stores the value passed in.
   * This action can be overridden.
   * @param _value
   */
  public void set (T _value)
  {
    value = _value;
  }

  /**
   * By default, returns the stored value.
   * This action can be overridden.
   * @return
   */
  public T get()
  {
    return value;
  }
}
Bill