简体   繁体   中英

Generics and subtyping

Create a class with a generic type T . A subclass of the class that defines a second type parameter, called V . Call the methods from both classes using the object. Create 2 objects with different objects

This is the question.

This is not homework if anyone might think. I am doing some java papers for practice. I don't understand how to "create 2 objects with different objects". Can anyone help?

class Gen<T> 
 {
  T obj;
  Gen(T ob)
  {
    obj = ob;
  }

 T getobj()
  {
    return obj;
  }
}

class Gen2<T, V> extends Gen<T>
{
  V obj1;
  Gen2(T ob,V ob1)
   {
    super(ob);
    obj1 = ob1;
   }

 V getobj1()
 { 
    return obj1;
 }

}

public class Ch2Lu4Ex3 
 {
  public static void main(String args[]) 
    {
      Gen2<String,String> g = new Gen2<String,String>("robin","raj");        

      System.out.println(g.getobj1());
      System.out.println(g.getobj());
    }
 }

The last part of the question:

Create 2 objects with different objects

Gen2<Integer,String> inst = new Gen2<Integer,String>(1, "robin");  

Well, you could do things like:

Gen<Integer> gen1 = new Gen<Integer>(10);
Gen2<Integer> gen2 = new Gen2<Integer,String>(10,"Hello");

Or you could combine them since they are on the same hierarchy.

Gen<Integer> gen1 = new Gen2<Integer,String>(10,"Hello");

Are you asking for something like:

Gen2<String,String> g = new Gen2<String,String>("robin","raj");
Gen2<Integer,Integer> h = new Gen2<Integer,Integer>(1, 2);  

Or am I misunderstanding your question?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM