0
class N<K> {

    K obj;

    N(K obj)
    {
        this.obj=obj;
    }

    public K getObject()
    {
        return this.obj;
    }
}

class temp
{
    public static void main(String[] args)
    {
        N<Double> a=new N<Double>(100.10); //Double type should not be allowed in generics
    
        N<String> b=new N<String>("hi");

        N<Integer> c=new N<Integer>(100);

        System.out.println(a.getObject()); // 'print 100.10'
        System.out.println(b.getObject());   // 'print hi'
        System.out.println(c.getObject());   // 'print 100'  
   
    }
}

Our code accepts all Type of data but i want only it to accept Integer and String type and other type should not be used ? How can i achieve the desired result.

1

1 Answer 1

3

There is no syntax to prevent someone from using other types. But you can prevent the creation of such object by making the constructor private and exposing two static methods like this :

public class N<K> {

  public static N<String> create(String value) {
    return new N<>(value);
  }

  public static N<Integer> create(Integer value) {
    return new N<>(value);
  }


  private final K obj;

  private N(K obj)
  {
    this.obj=obj;
  }

  public K getObject()
  {
    return this.obj;
  }
}

With this, you are sure that all instances of N are only for String and Integer types but you can still use thing like N<Float> for type declaration (for return type or function parameter for instance).

Another possibility is to use Sealed Classes but then you will need to create two extra classes one for String and one for Integer and you will still have the issue that N<Float> can still be used as a type :

public sealed class N<K> permits N.NString, N.NInteger {
  
  private final K obj;

  private N(K obj)
  {
    this.obj=obj;
  }

  public K getObject()
  {
    return this.obj;
  }

  public final static class NString extends N<String> {
    public NString(String obj) {
      super(obj);
    }
  }

  public final static class NInteger extends N<Integer> {
    public NInteger(Integer obj) {
      super(obj);
    }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.