Class Object and Method
 
Defining Classes
 
To define a class, we use the class keyword and the name of the class:
 
class MyClassName
{
...
}
 
By default, classes inherit from the Object class.
 
If this class is a subclass of another specific class (that is, inherits from another class), use extends to indicate the superclass of this class:
 
class myClassName extends mySuperClassName
{
...
}
 
Following is the code for a class called SimplePoint that represents a point in 2D space:
 
public class SimplePoint
{
public int x = 0;
public int y = 0;
}
 
This segment of code declares a class-- a new data type really-- called SimplePoint. The SimplePoint class contains two integer member variables, x and y. The public keyword preceding the declaration for x and y means that any other class can freely access these two members.
 
We create an object from a class such as SimplePoint by instantiating the class. When we create a new SimplePoint object space is allocated for the object and its members x and y. In addition, the x and y members inside the object are initialized to 0 because of the assignment statements in the declarations of these two members.
 
 
Ex:
public class SimpleRectangle
{
public int width = 0;
public int height = 0;
public SimplePoint origin = new SimplePoint();
}
 
Here the segment of code declares a class SimpleRectangle-- that contains two integer members, width and height.
SimpleRectangle also contains a third member, origin, whose data type is SimplePoint.
Here the class name SimplePoint is used in a variable declaration as the variable's type. We can use the name of a class anywhere we can use the name of a primitive type.
 
As with SimplePoint, when we create a new SimpleRectangle object, space is allocated for the object and its members, and the members are initialized according to their declarations.
 
The initialization for the origin member creates a SimplePoint object with this code: new SimplePoint() as illustrated here:
 
This diagram shows the difference between primitive types and reference types