We already talked about the fact that classes are complex data types. Now let's talk a little about the other side of classes — how classes are handled by the Java machine. Remember that in Java everything is an object, even a class. A class is an object. Does that surprise you? Then let's keep going.
Loading a class into memory
Actually, when a class is loaded into memory, three special "objects" are created:
Brief description of the illustration:
Yellow rectangle:
The code file is stored on disk as a file with the ".class" extension. It contains information about the class, its fields and methods, as well as the source code of methods compiled into bytecode.
Orange rectangle:
When the Java machine loads a class into memory, it compiles the bytecode into machine code specific to the computer's processor and operating system. Only the Java machine has access to this machine code. As Java programmers, we do not have access to it.
Green rectangle:
The Java machine creates an object that contains all the static variables and methods of the class. You access to this "object" using the class name.
For example, when you write java.lang.Math.PI
, you are referring to the static PI
variable located in the java.lang.Math
class. This java.lang.Math
object is our green rectangle. And that's where the static PI
variable is stored.
Blue rectangle:
When the Java machine loads the code of a class into memory, it creates a special java.lang.Class
object, which stores information about the loaded class: its name, method names, field names and types, etc.
The name "Class" can be a little confusing. It would make more sense to call it ClassInfo, since this class just stores some information about the loaded class.
You can get the Class object for any type using a command like this:
Class name = ClassName.class;
Examples:
Code | Note |
---|---|
|
Get a Class object with information about the String class |
|
Get a Class object with information about the Object class |
|
Get a Class object with information about the Integer class |
|
Get a Class object with information about the int type |
|
Get a Class object with information about the void type |
You can also get a reference to a class description object from any object, since each object has the getClass()
method, which it inherits from the Object
class.
Examples:
Code | Note |
---|---|
|
Same object as String.class |
|
Same object as Integer.class |
|
Same object as Boolean.class |
GO TO FULL VERSION