Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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_;   } }; 
like image 575
sivabudh Avatar asked Dec 06 '09 04:12

sivabudh


People also ask

Does Java have template classes?

Templates as in C++ do not exist in Java.

Are C++ templates and Java generics the same?

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.

What are template classes in Java?

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.


2 Answers

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.

like image 90
Laurence Gonsalves Avatar answered Sep 29 '22 16:09

Laurence Gonsalves


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.

like image 34
Moishe Lettvin Avatar answered Sep 29 '22 16:09

Moishe Lettvin