Thursday, 24 November 2016

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

OR

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 RectArea.java. After compiling RectArea.java 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.




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.putdata();
  r1.length = 15;
  r1.width = 25;
  r1.putdata();
 }
}
OUTPUT
C:\>javac RectArea.java
C:\>java RectArea
Length = 0
Width = 0
Length = 15
Width = 25

No comments:

Post a Comment