Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Nikos Blog Generic's Problem

 
Mohit G Gupta
Ranch Hand
Posts: 634
Chrome Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i unable to understand the following problems:
Problem-1


It give compile time error:non-static class T cannot be referenced from a static context

while the next code runs fine WHY



--------------------------------------
Problem-2


It gives compie time error:unexpected type,while the below code runs fine WHY




----------------------------------
Problem-3

It runs fine.while the below code gives error WHY



if i use ,then it runs fine

----------------------------------------
Problem-4


It gives the following error:

incompatible types
found : java.lang.String
required: String
String my = "Hello!";
^
1 error


WHY
-----------------------------------
 
Piotr Nowicki
Ranch Hand
Posts: 611
1
IntelliJ IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
AD Question-1

In the first example, you have a generic class with type T, which needs to be defined (exact type hiding behind the T) by creating a new Test class object.
At the same moment, the same type T is used for static method, which can be executed without creating a Test class object which cannot be made.

The second example runs, because you declare the <T> type within the static method - not on class level, so it's fine.

AD Question-2

Take a look here: http://www.angelikalanger.com/GenericsFAQ/FAQSections/ParameterizedTypes.html or more precisely here: http://www.angelikalanger.com/GenericsFAQ/FAQSections/ParameterizedTypes.html#FAQ103

AD Question-3

It is also related to the URL passed above. You can define a reference type to an array of concrete parametrized type, but you cannot instantiate this array.

AD Question-4

By saying this:



You are defining your own parametrized type named String (by convention, normally these are named like T or E). There is nothing preventing you from naming the generic type as the class name that already exist. Remember it has nothing with the extension of the class - it is just shadowing.

Therefore, the "my" reference variable is not a java.lang.String reference type, but your own String type reference, which cannot be assigned to String literal ("Hello!").
 
Aman Mehta
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Good to point out such depth things but in OCJP real exam it will not be such depth. If you take online training or if you read the books like K&B you will come to know at what level the questions are being asked in the exam.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic