java program for finding Area of rectangle and square using constructor overloading
/*Area and perimeter of rectangle and square using constructor overloading.
Constructor overloading means there will be two or more constructor and the name of all constructors will be same only number of arguments will be different.
when you pass arguments value in the constructor it matches the number of arguments value with the defined constructor arguments and executes that constructor automatically
Here Box is constructor.
*/
//Area of rectangle and square using constructor overloading.
import java.io.*;
import java.util.*;
//Instance variable of Box.
class Box{
double length;
double width;
//Constructor for rectangle when two parameter are passed (area).
Box(double l,double w){
length=l;
width=w;
}
double AreaRectangle(){
return length*width;
}
//Constructor for square when one value is initialized(area).
Box(double l){
length=l;
}
double AreaSquare(){
return length*length*length;
}
}
//Main class from where program execution begins
class Square_Rectangle_Const_Overloading{
public static void main(String args[]){
Box rectangle = new Box(10,20);
Box square = new Box(10);
System.out.println("Area of rectangle is " + rectangle.AreaRectangle());
System.out.println("Area of square is " +square.AreaSquare());
}
}
OUTPUT-
Area of rectangle is 200.0
Area of square is 1000.0
Constructor overloading means there will be two or more constructor and the name of all constructors will be same only number of arguments will be different.
when you pass arguments value in the constructor it matches the number of arguments value with the defined constructor arguments and executes that constructor automatically
Here Box is constructor.
*/
//Area of rectangle and square using constructor overloading.
import java.io.*;
import java.util.*;
//Instance variable of Box.
class Box{
double length;
double width;
//Constructor for rectangle when two parameter are passed (area).
Box(double l,double w){
length=l;
width=w;
}
double AreaRectangle(){
return length*width;
}
//Constructor for square when one value is initialized(area).
Box(double l){
length=l;
}
double AreaSquare(){
return length*length*length;
}
}
//Main class from where program execution begins
class Square_Rectangle_Const_Overloading{
public static void main(String args[]){
Box rectangle = new Box(10,20);
Box square = new Box(10);
System.out.println("Area of rectangle is " + rectangle.AreaRectangle());
System.out.println("Area of square is " +square.AreaSquare());
}
}
OUTPUT-
Area of rectangle is 200.0
Area of square is 1000.0
Thanks for sharing this post. Java Program to Calculate Area and Perimeter of Rectangle .
ReplyDelete