Constructor

Write a Java Program to define a class Rectangle, Constructor based program

Write a Java Program to define a class Rectangle which has following descriptions:

Data Members/Instance Variables: length, breadth

Member Functions/Methods:

  • Rectangle( ) – default constructor to initialize length and breadth with 0.
  • Rectangle( int, int) – parameterized constructor to initialize data members.
  • input( ) – function to accept the values from user.
  • display( ) – function to display the values of length and breadth.
  • area( ) – function to calculate the area of rectangle.

Write a main( ) method where user will create an object of the class and call all the member functions.

import java.io.*;
import java.util.*;
	
	class Rectangle
	{
		int length;
		int breadth;
		Rectangle( )				//default constructor
		{
			length = 0 ;
			breadth = 0 ;
		}
		Rectangle( int x, int y )		//parameterized constructor
		{
			length = x ;
			breadth = y ;
               }
		void input( )				//input function
		{
			Scanner sc = new Scanner(System.in) ;
			System.out.println(“Enter length = ”);
			length = sc.nextInt( );
			System.out.println(“Enter breadth = ”);
			breadth = sc.nextInt( );
		}
		void display( )				//display function
		{
			System.out.println(“Length =” + length);
			System.out.println(“Breadth =” +breadth);
		}
		void area( )				//area function
		{
			int Ar = length * breadth ;
			System.out.println(“Area of Rectangle = ” + Ar);
		}		
		public static void main (String arg [ ])	
		{
			Rectangle ob = new Rectangle( );
			ob.input( );
			ob.display( );
			ob.area( );
			
			Rectangle pm = new Rectangle( 8, 4 );
			pm.display( ); 
			pm.area( );
		}
	}

Click to comment

Leave a Reply

Your email address will not be published. Required fields are marked *

To Top