This site requires JavaScript, please enable it in your browser!
Greenfoot back
earnold
earnold wrote ...

2017/1/22

Specifying parameters of type java.lang.Class

earnold earnold

2017/1/22

#
Hi Programmers! I'm still learning Java in Greenfoot, and this is likely a simple answer - I'm just a bit confused though as to why you specify a parameter of type java.lang.Class with the word .class after the class name. For instance, if ( isTouching(Worm.class)) { removeTouching(Worm.class); } Why is the argument (Worm.class) instead of some other dot notation or variable declaration? Just curious if anyone could help explain this in a bit more detail. Thanks so much in advance.
Nosson1459 Nosson1459

2017/1/23

#
Worm.class is a type of file not a variable, when you're doing Worm.class you're seeing if you are touching the actor which the file is Worm.class with the already compiled code. When you edit the Worm class you are editing the Worm.java file, then compiling it.
danpost danpost

2017/1/23

#
From what I understand, 'Worm' would be a Type and 'Worm.class' is a Class instance, where the following is true:
1
2
3
// Worm.class == new Worm().getClass()
//     and
// Worm.class == Class<Worm>
Types are used as above, to acquire the Class instance as well as to declare what a variable is to hold:
1
Worm worm = new Worm();
You could even say that 'Worm' on the right side in the last snippet is referring to a Type of object and not to the Class instance (you need a Type before you can get an instance of it); and the declaration line of the class uses the word 'class' to indicate what it is. Hope this helps (at least a little).
earnold earnold

2017/1/24

#
Thank you both.
davmac davmac

2017/1/24

#
danpost wrote...
1
// Worm.class == Class<Worm>
This is not quite correct; the type of Worm.class is Class<Worm>. So, for instance, it is possible to write something like:
1
Class<Worm> wormClass = Worm.class;
So, Worm and Class<Worm> are both types, but they are different types: one is the type of the Class instance of the other.
danpost danpost

2017/1/24

#
davmac wrote...
This is not quite correct; the type of Worm.class is Class<Worm>. So, for instance, it is possible to write something like: < Code Omitted> So, Worm and Class<Worm> are both types, but they are different types: one is the type of the Class instance of the other.
I had a strong suspicion that I was getting something wrong there (was having a hard time trying to express my answer). Thank for the clarification.
You need to login to post a reply.