Create class Rectangle with getdata() and putdata() methods

class is a collection of objects that has common properties. It is a template for an object, and an object is an instance of a class. A class is declared by use of the class keyword. It has the following general syntax:
class <classname> {
    type instance-variable1;
    type instance-variableN;
 type methodname1(parameter-list) {
  // body of method
 type methodnameN(parameter-list) {
  // body of method
Where, type is the data type of a variable which it may hold. A method has a return type such as voidint, etc. Creating an object is referred to an object. Objects of specific class are created using new operator which returns reference of that object. The syntax for creating an object of class is shown below:
class_name  object_name;            // Create object reference

object_name  =  new  class_name( );   // Instantiating object of class


class_name  object_name  =  new  class_name( );  // Creating object

In this program, we have created a Rectangle3 class that have two data members length and width. And we have created two methods getdata( ) and putdata( ) which gets the data and displays the data respectively. We are created the object of the Rectangle3 class by using new keyword and printing the objects value. Save this file by name After compiling file we get two class files one is Rectangle3.class and other is RectArea.class then use RectArea.class file for running the program.

Note: Remember that you have to pass the class file name which contains the main( ) function while running the program.

class Rectangle3 {
 int length, width;
 void getdata(int a, int b) {
  length = a;
  width = b;
 void putdata() {
  System.out.println("Length = "+length);
  System.out.println("Width = "+width);

public class RectArea {
 public static void main(String args[]) {
  Rectangle3 r1 = new Rectangle3();
  r1.length = 15;
  r1.width = 25;
C:\>java RectArea
Length = 0
Width = 0
Length = 15
Width = 25


Post a Comment

Popular posts from this blog

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.

Program to draw Smiley in Applet