All the Notes in one Place. Download our Official App from Google Play.

Java Constructors

                                    Java Constructors

A Constructor initializes an object immediately upon creation. It has the same name as the class in which it resides and is syntactically similar to a method. Once defined, the constructor is automatically called immediately after the object is created, before the new operator completes. Constructors have no return type.

Here is exp:

/*
         This is Java Program Showing Use Constructors.
          Program developed by #Asad Hussain
         This file name is "expconstructor.java".
*/
import java.util.*;
class Rectangle {
    double width;
    double length;

    Rectangle() {
        System.out.println("Constructor in work");
        width = 95;
        length = 45;
}
    double area() {
        return length * width;

}

}
public class expconstructor{
    public static void main(String args[]){
   
        Rectangle myrectangle1 = new Rectangle();
        Rectangle myrectangle2 = new Rectangle();
        double area;

        area = myrectangle1.area();
        System.out.println("Area is " + area);

        area = myrectangle2.area();
        System.out.println("Area is " + area);
}
}
   

Output of this Program:   

http://javac0.blogspot.com/2015/01/java-constructors.html
Java Program Showing Use constructor by Asad Hussain

Written By: Asad Hussain

Post a Comment

Previous Post Next Post