Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it not an error to call a non-parameterized method with type arguments?

Tags:

java

generics

I have the following Java program that I was expecting to not compile, but it did:

class Test {
    public static void f() {
    }

    void m() {
            Test.<String>f();
    }
}

Why does javac allow calling a non-parameterized method in this way?

My Java compiler version is: javac 1.7.0_75

like image 682
user11171 Avatar asked Feb 18 '15 13:02

user11171


People also ask

What is non parameterized method?

Non-Parameterized methods: These methods do not have any parameter-list. The programmer can simply call the function without sending any values to the function.

Why is parameterized type important in Java?

How Can You Use Generics? Type parameters, also known as type variables, are used as placeholders to indicate that a type will be assigned to the class at runtime.

Why are parameterized types important?

Types defined using parameters are called parameterized types. Parameterized types perform an important role in Haskell, as they allow you to define generic data structures that work with a wide range of existing data.


1 Answers

The explicit type parameter is simply ignored.

This is stated in JLS, Section 15.12.2.1:

  • If the method invocation includes explicit type arguments, and the member is a generic method, then the number of type arguments is equal to the number of type parameters of the method.

This clause implies that a non-generic method may be potentially applicable to an invocation that supplies explicit type arguments. Indeed, it may turn out to be applicable. In such a case, the type arguments will simply be ignored.

like image 145
Konstantin Yovkov Avatar answered Oct 29 '22 14:10

Konstantin Yovkov