Category Archives: Classes, Object & Methods

Default & Parameterized constructor :

The default constructor are used to initialize the object variables with some default values at the time of object instantiation. Which constructor has arguments thats called Parameterized Constructor.  

<br />class Rectangle {
int length;
int breadth;
Rectangle() //Default constructor

{
length = 0;
breadth = 0;
}
Rectangle(int len,int bre) // Parameterized constructor
{
length = len;
breadth = bre;
}
void rectArea()
{
int result;
result = length * breadth ;
System.out.println("The area of the rectangle is : " + result );
}
}
class RectangleDemo {
public static void main(String args[]) {

Rectangle r1 = new Rectangle(); //calling default constructor
Rectangle r2 = new Rectangle(5,10); // calling parameterized constructor

r1.rectArea();
r2.rectArea();

}
}

Output :-
java1

Constructor Declaration :

A constructor is a special type of method that enables an object to initialize itself when it is created. Constructors have the same name as the class itself and they do not specify a return type.

class Sum
{
int first;
int second;
}
Sum (int x, int y) // Constructor method
{
first = x ;
second = y ;
}
int result()
{
return ( first + second );
}
}

Fields Declaration :

We can Declare the instance variable exactly the same way as we declare local variables.

class Rectangle
{
int length;
int height;
}

Note: These variables are only declared and therefore no storage space has been created in the memory.Instance variables are also known as member variables.

Defining a class :

A class is a user defined data type with a template that serves to define its properties.It is a blueprint from which individual objects are created.In java variables are termed as Instances of classes, which are the actual Objects.

The basic form of a class definition is :

class classname [extends superclassname ]
{
[ fields declaration; ]
[ methods declaration; ]
}

The keyword extends indicates that the properties of  superclassname class are extended to the classname class.
Fields and methods are declared inside the body.