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

后端 未结 4 1719
一向
一向 2020-12-29 05:28

How do I write an equivalent of this in Java?

// C++ Code

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

public:
  SomeClass()
  {
  }
  vo         


        
相关标签:
4条回答
  • 2020-12-29 06:03
    /**
     * 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;
      }
    }
    
    0 讨论(0)
  • 2020-12-29 06:06

    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.

    0 讨论(0)
  • 2020-12-29 06:10
    public class GenericClass<T> {
        private T data;
    
        public GenericClass() {}
    
        public GenericClass(T t) {
            this.data = t;
        }
    
        public T getData() {
            return data;
        }
    
        public void setData(T data) {
            this.data = data;
        }
    
        // usage 
        public static void main(String[] args) {
            GenericClass<Integer> gci = new GenericClass<Integer>(new Integer(5)); 
            System.out.println(gci.getData());  // print 5; 
    
            GenericClass<String> gcs = new GenericClass<String>(); 
            gcs.setData("abc");
            System.out.println(gcs.getData());  // print abc;
        }
    }
    
    0 讨论(0)
  • 2020-12-29 06:28
    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.

    0 讨论(0)
提交回复
热议问题