Logo 
Search:

Java Articles

Submit Article
Home » Articles » Java » FundamentalRSS Feeds

Adding Constructors in a Class

Posted By: Rainart Fischer     Category: Java     Views: 8153

This article explains about how to ad constructors in a class using example in a java.

An object will require form of initialization when it is created. To accommodate this, java allows you to define constructors for classes.

A constructor is a special method that creates and initializes an object of a particular class. It has the same name as its class and may accept arguments.

It is similar to any other method. It does not have a return type. But it returns a reference to the object that it creates. If you do not explicitly declare a constructor for a class, the java compiler automatically generates a default constructor that has no arguments.

A constructor is never called directly. It is invoked by the new operator.  

Syntax of Constructor

className(cparam)
{
// body of constructor
}

Example of Constructor

Example 1 : Program to create a class Square having height and width variables and constructor which assigns default values to variables

class Square
{
       int height;
       int width;

       Square()
       {
               height = 0;
               width = 0;
        }
}

class ImplSquare
{
     public static void main(String args[])
     {
             Square sObj = new Square();
             
             System.out.println("Object height =  " + sObj.height);
             System.out.println("Object width = " + sObj.width);
      }
}


Output

Object height =  0
Object width =  0
  
Share: 

 
 

Didn't find what you were looking for? Find more on Adding Constructors in a Class Or get search suggestion and latest updates.

Rainart Fischer
Rainart Fischer author of Adding Constructors in a Class is from Frankfurt, Germany.
 
View All Articles

 
Please enter your Comment

  • Comment should be atleast 30 Characters.
  • Please put code inside [Code] your code [/Code].

 
No Comment Found, Be the First to post comment!