Reputation: 198398
In Java, when you define a class, you are defining a type implicitly. Say, I defined a class User
:
class User {}
Then we get a class User
and an implicit type User
.
When we use the name User
, sometimes we are referencing class User
, sometimes type User
. Let me give some examples:
User user = new User();
^^^^(1) ^^^^(2)
public void saveUser(User user) {
^^^^(3)
}
class Dao<T> {
def save(T t) {}
}
new Dao<User>();
^^^^(4)
Class cls = User.class;
^^^^(5)
User user = (User) someObj;
^^^^(6)
My understandings:
(1)
is type User
(2)
is the constructor of class User
(3)
is type User
(4)
is type User
(5)
is class User
(6)
is type User
Is my understanding correct?
Upvotes: 3
Views: 107
Reputation: 2040
I would say:
Class cls = User.class;
^^^^^^^^^^(5)
User user = new User();
^^^^^^^^^^(7)
User
User
(not the constructor, the constructor may exists only i a subclass of User)User
User
of a definition of a generic default constructor of type Dao
User
.User
.User
.Type or Class? Every Class can be a type, not every type can be a Class. Primitives like int
for example, is a type but not a Class. If you are perfect-scientific-correct, you must specify that User
is a Class. If you say User
is a type, its not wrong but also not specific.
Upvotes: 3
Reputation: 9816
User
is the type, user
a reference to an object of that type; new User()
creates a new instance of type User
; that instance gets assigned to the reference user
;saveUser
a reference to an object of type User
;User
is a type parameter, that is, it specifies which object type the Dao
class is parameterized by;Class<User>
, which represent the type User
, it is technically not the User
type;someObj
is of type User
and assigning the value of that reference to the reference user
(which has type User
); depending on the type of someObj
the cast might or not be required by the compiler and might or might not cause a ClassCastException
.Upvotes: 1
Reputation: 6622
A class is an example of abstract data type. So, a class IS a type and you can indifferently name User "class" or "type".
Mind that the opposite is not always true, so a type is not necessarily a class (for example primitive types like int float,ecc. )
Upvotes: 0
Reputation: 5187
Position (2)
represents the object itself instantiated by calling the constructor
with no arguments.
All other assumptions are right.
Upvotes: 0