Basics

Write a Java Program to define a class Rectangle, Class and Object based Program

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

Data Members/Instance Variables: length, breadth

Member Functions/Methods:

  • 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;
		void input( )
		{
			Scanner sc = new Scanner(System.in) ;
			System.out.println(“Enter length = ”);
			length = sc.nextInt( );
			System.out.println(“Enter breadth = ”);
			breadth = sc.nextInt( );
		}
		void display( )
		{
			System.out.println(“Length =” + length);
			System.out.println(“Breadth =” +breadth);
		}
		void area( )
		{
			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( );
		}
	}

Click to comment

Leave a Reply

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

To Top