Conceptually, a Class is a description of state and behavior. An Object (an instance) is a data structure containing that state and behavior.
For example, given a class
class User {
String name;
void setName(String name) {
this.name = name
}
}
The class User
has behavior and state, ie. it has a Field
called name
and a Method
called setName
. The above describes this behavior. If you create an instance
User user = new User();
user.setName("Jon");
you now have a data structure containing actual state and exhibiting behavior.
In Java, you have what is called Reflection which basically describes the metadata of a Class, its state, and its behavior. This is interpreted as instances of Class
, Field
, and Method
classes, respectively.
In the example above, since the field name
itself has state and behavior (it has a name ("name"), we can read it or write to it), there is a class that must describe it. The class that describe that state and behavior is Field
and instances of Field
contain the state and behavior.
Similarly, the Method
class describes a method. A method has a state, its name ex. setName
, the arguments it accepts, ex. a String
. It also has behavior, ex. it returns void (doesn't return anything).
Finally, you have the class Class
which describes the state and behavior of a class. Instances of Class
describe the state and behavior of a class. For example, the Class
instance for the User
class will have a Field
object and a Method
object (it actually has more than that, but bear with me). Fields and methods are state of a class. The behavior is, for example, creating an instance of the class.