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_; } };
Templates as in C++ do not exist in Java.
A C++ template gets reproduced and re-compiled entirely whenever a template is instantiated with a new class. The main difference is that Java generics are encapsulated. The errors are flagged when they occur and not later when the corresponding classes are used/instantiated.
A class is a template for creating a particular form of object. A Java class definition corresponds to a C++ struct definition generalized to include all of procedures that process objects of the defined class. In Java, all program code must be part of some class.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With