简体   繁体   English

实例化具有与其超类相同类型的泛型类型对象

[英]Instantiating a generic type object with the same type as its superclass

I am wondering if it is possible to create objects that are of generic type with the same type as the class it is contained in.我想知道是否可以创建与它所包含的类具有相同类型的泛型类型的对象。

For example, consider this object例如,考虑这个对象

public class Foo<T> {

   private T variable;

   Foo() {

   }
}

Now consider this现在考虑这个

public class Bar<T> {

   private Foo foo;

   Bar() {
      foo = (T) new Foo();
   }
}

I want the data type of the foo object inside the bar class to be the same data type that bar is instantiated as.我希望 bar 类中的 foo 对象的数据类型与 bar 实例化的数据类型相同。

Yes you can do like this and it will work.是的,你可以这样做,它会起作用。 But you need to have correct oveloaded constructors to handle the data types.但是您需要有正确的重载构造函数来处理数据类型。

The output of the program is:程序的输出是:

class java.lang.Integer
class java.lang.String

As you can see the datatype for foo variable is same as the datatype of Bar object.如您所见, foo 变量的数据类型与 Bar 对象的数据类型相同。

And you have made one mistake in the program there should be an overloaded constructor in the Bar class.而且您在程序中犯了一个错误,Bar 类中应该有一个重载的构造函数。

package test;

public class test {

    public static void main(String[] args) {
        Bar<Foo> integerBar = new Bar(3);
        Foo<Integer> fooIntegerObject = (Foo) integerBar.getFoo();

        Bar<Foo> stringBar = new Bar("hello");
        Foo<String> fooStringObject = (Foo) stringBar.getFoo();

        System.out.println(fooIntegerObject.getVariable().getClass());
        System.out.println(fooStringObject.getVariable().getClass());

    }
}

class Foo<T> {

    private T variable;

    Foo(T x) {
        variable = x;
    }
    public T getVariable() {
        return variable;
    }

}

class Bar<T> {

    private T foo;

    Bar(T x) {
        foo = (T) new Foo<T>(x);
    }
    public T getFoo() {
        return foo;
    }

}

The constructor in Foo requires an argument; Foo 中的构造函数需要一个参数; but you can do this:但你可以这样做:

public class Bar<T> {

   private Foo<T> foo;

   Bar(T x) {
      foo = new Foo<T>(x);
   }
}

Based on your updated question, the following will work:根据您更新的问题,以下内容将起作用:

class Bar<T extends Foo<T>> {  
    private Foo<T> foo;

    Bar() {
        foo = new Foo<T>();
    }
}

Note that you shouldn't use a raw type Foo .请注意,您不应使用原始类型Foo

I'm not sure if I understand you correctly, but do you want something like this?我不确定我是否理解正确,但你想要这样的东西吗?

        public class Bar<T> extends Foo<T> {

           private Foo<T> foo;

           Bar() {
              foo = new Foo<T>();
           }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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