Meaningless Drivel is fun!
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Nikos Blog  Generic's Problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Nikos Blog  Generic Watch "Nikos Blog  Generic New topic

Nikos Blog Generic's Problem

Mohit G Gupta
Ranch Hand

Joined: May 18, 2010
Posts: 634

i unable to understand the following problems:

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

while the next code runs fine WHY


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


It runs fine.while the below code gives error WHY

if i use ,then it runs fine


It gives the following error:

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


OCPJP 6.0 93%
OCPJWCD 5.0 98%
Piotr Nowicki
Ranch Hand

Joined: Jul 13, 2010
Posts: 610

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: or more precisely here:

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

Joined: Sep 25, 2013
Posts: 1
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.
subject: Nikos Blog Generic's Problem
It's not a secret anymore!