实例化与其超类

时间:2017-10-09 07:44:45

标签: java generics types

我想知道是否可以创建具有与其所包含的类相同类型的泛型类型的对象。

例如,考虑这个对象

public class Foo<T> {

   private T variable;

   Foo() {

   }
}

现在考虑一下

public class Bar<T> {

   private Foo foo;

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

我希望bar类中foo对象的数据类型与bar实例化的数据类型相同。

4 个答案:

答案 0 :(得分:0)

是的,你可以这样做,它会起作用。但是你需要有正确的开发构造函数来处理数据类型。

该计划的输出是:

<script>
  angular.module('ngPatternExample', [])
  .controller('ExampleController', ['$scope', function($scope) {
    $scope.regex = '\\d+';
  }]);
</script>

正如您所看到的,foo变量的数据类型与Bar对象的数据类型相同。

你在程序中犯了一个错误,Bar类中应该有一个重载的构造函数。

<div ng-controller="ExampleController">
 <form name="form">
  <label for="regex">Set a pattern (regex string): </label>
  <input type="text" ng-model="regex" id="regex" />
  <br>
  <label for="input">This input is restricted by the current pattern: 
  </label>
  <input type="text" ng-model="model" id="input" name="input" ng-pattern="regex" /><br>
  <hr>
  input valid? = <code>{{form.input.$valid}}</code><br>
  model = <code>{{model}}</code> 
 </form>
</div>

答案 1 :(得分:0)

Foo中的构造函数需要一个参数;但你可以这样做:

public class Bar<T> {

   private Foo<T> foo;

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

答案 2 :(得分:0)

根据您更新的问题,以下内容将有效:

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

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

请注意,您不应使用原始类型Foo

答案 3 :(得分:-1)

我不确定我是否理解你,但你想要这样的东西吗?

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

           private Foo<T> foo;

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