What is the purpose of type arguments in constructor call following new?

后端 未结 2 1473
伪装坚强ぢ
伪装坚强ぢ 2021-01-02 05:00

In the Java specification (http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.9), new has the following form:

ClassInstanceCreationExpressio         


        
2条回答
  •  旧巷少年郎
    2021-01-02 05:31

    Constructors can declare type parameters too

    public class Main {     
        public static class Foo {
            public  Foo(T object, E object2) {
    
            }
        }
        public static void main(String[] args) throws Exception {
            Foo foo = new  Foo(1, "hello");           
        }    
    }
    

    That's what the preceding the constructor call is for. It is the type argument for the constructor.

    The following

    Foo foo = new  Foo(1, new Object());
    

    fails with

    The parameterized constructor Foo(Integer, String) of type Main.Foo is not applicable for the arguments (Integer, Object)

    In your last

    Foo t5 = new  Foo();  // fails -- NotDefined is undefined
    

    NotDefined is just not a type that is found during compilation. If it was, it would just give you a warning that it is unused.

提交回复
热议问题