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);
}
}
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:
Java Program Showing Use constructor by Asad Hussain |
Post a Comment