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_;
}
};
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_;
}
};
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.
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.
/**
* 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;
}
}