Chapter 5 Classes



Chapter 5  Classes
class:
A class is a user-defined data types with a template that serves to define its properties. The basic form of a class definition is :
class classname [extends superclassname]
{
[variable declaration]
[method declaration]
}
Example :
class Rectangle
{
int length;
int width;
void getdata(int x, int y)
{
length=x;
width=y;
}
}
object :
An object in java is essentially a block of memory that contains space to store all the instance variable.
objects in java are created using new operator. The new operator creates an object of the specified class and returns a reference to that object.
Example :
Rectangle rect1;//declare
rect1 = new Rectangle();
Both statement can be combined into one as shown below :
Rectangle rect1= new Rectangle;

Constructor :
All objects that are created must be given initial value. Java supports a special type of method, called constructor, that enables an object to initialize itself when it is created.
Constructor have the same name as the class itself. They do not specify a return type, not even void.
Example :
class Rectangle{ 
int length;
int width;
 Rectangle(int x, int y) // constructor
{
length=x;
width=y;
}
}