Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how type variable allowing wrong type?

package org.my.java;

public class TestTypeVariable {

    static <T,A extends T> void typeVarType(T t, A a){
        System.out.println(a.getClass());
        System.out.println(t.getClass());
    }

    public static void main(String[] s){
        int i= 1;
        typeVarType("string", i);
    }
}

when run, following is the output :

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

How can A be of type Integer when it has been already upper-bounded to String?

Please explain me on it.

like image 912
Atul Avatar asked Sep 25 '17 08:09

Atul


People also ask

Can two variables of different types have the same name?

Yes, variables belonging to different function can have same name because their scope is limited to the block in which they are defined. Variables belonging to different functions in a single code can have same name if we declare that variable globally as shown in the following code snippet below .

Can variables change type in Java?

You can change the data type for a variable at any time by using the variable Type setting in the Variables tab. Existing values are converted to the new type.

What does error .class expected mean?

The class interface or enum expected error is a compile-time error in Java which arises due to curly braces. Typically, this error occurs when there is an additional curly brace at the end of the program.

Which one of the following options is the correct name for empty type parameter?

It is called generics.


1 Answers

Two things here:

  • there is a simple solution to the "bad" typing: T isn't String but Object. And Integer extends Object. But please note: this only works with the "enhanced" type inference capabilities of Java8. With Java7, your input will not compile!
  • misconception on your end: getClass() happens at runtime, and therefore returns the specific class of the objects passed - independent on what the compiler thinks about generics at compile time.
like image 153
GhostCat Avatar answered Sep 24 '22 07:09

GhostCat