In essence, a class definition is very simple. There are just two kinds of things that you can include in a class definition:
- Fields : These are variables that store data items that typically differentiate one object of the class from another. They are also referred to as data members of a class.
- Methods : These define the operations you can perform for the class so they determine what you can do to, or with, objects of the class. Methods typically operate on the fields the variables of the class.
- Non-static fields, also called instance variables : Each object of the class will have its own copy of each of the non-static fields or instance variables that appear in the class definition. Each object will have its own values for each instance variable.
- Static fields, also called class variables : A given class will have only one copy of each of its static fields or class variables, and these will be shared between and among all the objects of the class. Each class variable exists even if no objects of the class have been created.
Analogous to the variables in a class definition are two varieties of methods instance methods and class methods. You can execute class methods even when no objects of a class exist, whereas instance methods can be executed only in relation to a particular object, so if no objects exist, you have no way to execute any of the instance methods defined in the class. Again, like class variables, class methods are declared using the keyword static, so they are sometimes referred to as static methods.
Constructors
A constructor is a special kind of method that is always invoked when you create an object. A constructor has two special characteristics that differentiate it from other class methods:
- A constructor never returns a value, and you must not specify a return type—not even of type void.
- A constructor always has the same name as the class.
No comments:
Post a Comment