When you define a class, you declare its exact form and nature.
You do this by specifying the instance variables
that it contains and the methods that operate on them.
Although very simple classes might contain only
methods or only instance variables,
most real-world classes contain both.
A class is created by using the keyword class.
The general form of a class definition is shown here:
class classname {
// declare instance variables
type var1;
// declare methods
type method1(parameters) {
// body of method
}
}
Classes as Data Types
An object is just an instance of a data type.
For example, when you declare a variable of type int,
you're creating an instance of the int data type.
A class is like a data type in that it is the blueprint upon which an object is based.
When you need a new object in a program,
you create a class, which is a kind of template for the object.
Then, in your program, you create an instance of the class.
This instance is called an object.
Constructor
A constructor initializes an object when it is created.
It has the same name as its class and is syntactically similar to a method. However, constructors have no explicit return type.
Typically, you will use a constructor to give initial values to
the instance variables defined by the class,
or to perform any other startup procedures
required to create a fully formed object.
All classes have constructors, whether you define one or not,
because Java automatically provides a default constructor
that initializes all member variables to zero.
However, once you define your own constructor,
the default constructor is no longer used.