7 Classes and Objects

7.1 INTRODUCTION

A class is a basic unit of encapsulation and abstraction. It binds together data and methods that work on data. The class is an abstract data type (ADT) so the creation of a class simply creates a template. As discussed in the beginning of the Chapter 1, each and everything has to be defined within the class. The data members of the class are called field and the member functions are known as methods. The general syntax of creating a class in Java is shown as below.

class Class_name
{
   type member_variable1;
   type member_variable2;
   //..................
   type member_variable3;
   type methodname1(parameter-list)
   {
          //body of method
   }
   type methodname2(parameter-list)
   {
          //body of method
   }
   type methodnameN(parameter-list)
   {
          //body of method
   }
}

The class is a keyword. Following this keyword, class. class_name represents the name of the class. The class name must obey the rules of writing an identifier as the class_name is nothing but an identifier. The class is opened by opening brace ({) and closed by closing brace (}). Inside the class, data member and member functions are defined. The type/mode may be public, private or protected . If no type is specified then default type is assumed, which is known as friendly default. There are three different types of modes: public, private and protected . The mode is also known as visibility modifier or access specifier. All public data members and methods declared as public/protected can be used inside and outside the class. Private data members and functions can be used only inside the class. To know more about access specifier, see the chapter 'Package and Interface'.

The data members of the class are used inside the member functions of the class. The data members are declared inside the class but used in the member functions of the class. Usually the data members are private and the member functions are public. So the data members can be used only inside the functions of the class. This is to safeguard private data from external access.

If no visibility mode is written, the default visibility mode is assumed for the class.

The declaration of a class alone does not serve any purpose. To make use of the class a variable of type class needs to be created. A variable of class type is known as an object. The class is loaded into memory when the first object of the class is created. The type of class defines the nature and shape of the object. The creation of object creates the memory space for it which depends on the size of the data members of the class. For each object, a separate copy of the data members is created. On the other hand, only one copy of the member function is created, which is shared by all the objects. The objects are also termed as instances of the class.

The objects call the member functions of the class using operator '.' which is known as period or membership operator.

Before a member function can work on to the data member of the class, they must be initialized by calling a function that provides initial values to the data member of the class.

Consider the dummy class as given below.

class demo
{
}

This creates an empty class named demo . To create an object of the class demo the following is written:

demo d;
d= new demo ();

In Java, the line demo d; creates only a reference for an object of class demo type. This does not create object at all. In Java, no object is created statically. All objects are created dynamically using the new operator and constructor method of the class. (A constructor is a member function of the class whose name is the name of the class). The second line d = new demo (); actually creates an object from the heap and the object d starts pointing to the newly created object of class demo type. This can be shown in Figure 7.1 (a-b).

images

Figure 7.1 (a) Reference 'd' pointing no where (b) 'd' contains reference of objects

A new class with fields (data members) and methods (member functions) is given below:

class demo
{
   int num;
   void input(int x)
   {
          num = x;
   }
   void show()
   {
          System.out.println("num=" + num);
   }
}

In Java, the default visibility modifier is default public or friendly public . It is not pure public. The meaning of this is explained in detail in the chapter entitled 'Package and Interface'. But for the time being, assume it is similar to public. Therefore, everything in the class is public . All fields of the class are known as instance variable and the methods are instance method . An object of a class is usually termed as instance of a class. In Java, each method or field must be separately assigned an access specifier. For example, in order to make num private and show protected in the above class, the following syntax can be written:

private int num;
protected void show(){
   System.out.println("num="+num);
}

Every method has to be defined within the class. A method cannot be declared inside a class and definition outside the class. The methods in Java determine the messages an object can receive. For example, one can call the method show as assuming d is an object of class demo and initialize d.show(). This act of calling a method is commonly referred to as sending a message to an object. In the preceding example, the message is show () and the object is d. Object-oriented programming is often summarized as simply 'sending messages to objects'. For each object a separate storage is allocated depending on the size of the fields within the class. A field is an object of any type that can be communicated with by its reference. The fields may be primitive data types or references to objects of other classes; in case of reference, fields may be primitive data types before it can be put to use. The primitive data types as members of the class posses default values if not initialized. They are listed in Table 7.1.

S. No. Primitive Type Default Value
1 boolean False
2 char (null)
3 byte (byte)0
4 short (short)0
5 int 0
6 long 0L
7 float 0.0f
8 double 0.0d

Table 7.1 Default values of data types for class

For char, the default value is not printed, rather a blank space will be visible. See the following program.

class demo
{
   int x;
   float y;
   char z;
   double d;
   boolean b;
}
class JPS1
{
   public static void main(String[] args)
   {
          demo d = new demo();
          System.out.println(d.x + " " + d.y + " " + d.z);
          System.out.println(d.d + " " + d.b);
   }
}

OUTPUT:

0  0.0
0.0 false

To access any of the field or method the dot operator can be used. For example, to access num and show in the earlier class example the following can be written:

demo dd=new demo();
dd.num=20;
dd.show();

7.2 PROGRAMMING EXAMPLES

/*PROG 7.1 DEMO OF CLASS VER 1 */
class demo
{
   private int cx, cy;
   void input(int x, int y)
   {
          cx = x;
          cy = y;
   }
   void show()
   {
          System.out.println("cx=" + cx);
          System.out.println("cy=" + cy);
   }
}
class JPS2
{
   public static void main(String args[])
   {
          demo d = new demo();
          d.input(10, 20);
          d.show();
   }
}

OUTPUT:

cx=10
cy=201

Explanation: A class is created using the keyword class followed by the class name. The class name follows the rules of writing identifiers. Inside the class demo, there are two variables cx and cy of type integer. Before the cx and cy is written 'private' so they become private. If private is not written, they are considered as default public. The function input_data takes two parameters of type int and returns nothing as void in the return type. The function show_data displays the two data members' cx and cy.

In the main, the statement demo d = new demo (); creates an object of the class demo type. The variable d of class demo type is known as an instance of the class demo or an object. The creation of an object allocates memory depending on the size of the class which is the sum of the size of the data member. The functions do not add to the size of the class or object. Here, a memory of 8 bytes are allocated for the object d . The functions are given memory when a class is loaded into the memory.

All public members (data + function) can be accessed in the main with the help of object using dot (.) operator, which is also known as membership operator or period.

Through statement d1.input_data (10, 20) the function input_data is called and two int constants, 10 and 20 , are passed. They are collected in the formal parameters x and y and then assigned to cx and cy . Now, cx and cy can be used in all the functions of class demo. While working with the class and object, the first thing that needs to be performed is to assign values to data members of the class through function or they can be initialized within the class itself. As cx and cy now contain the valid values, statement d1.show_data () displays the values of cx and cy through System.out. pritln. Note that as cx and cy are private they can be accessed only inside the member function of the class and not anywhere. Usually, data members are made as private and member function as public while designing a class.

/*PROG 7.2 DEMO OF CLASS VER 2, INITIALIZING DATA MEMBERS WITHIN THE CLASS */
import java.io.*;
import java.util.*;
class demo
{
   private int cx = 20, cy = 40;
   void show()
   {
         System.out.println("cx = "+cx+"	cy = "+cy);
   }
}
class JPS3
{
   public static void main(String args[])
   {
         demo d = new demo();
         d.show();
         demo d1 = new demo();
         d1.show();
   }
}

OUTPUT:

cx=10
cy=20

Explanation: The program is similar to the previous one with the difference that the data members of the class are initialized within class itself and created two objects instead of one. The disadvantage of initializing data members within the class is that all the objects share the same initialized value. In the earlier program, each object can initialize its own data members using call to function.

If cx and cy of the data members were not private then their values could be changed outside the class in the following way:

d.cx = 10; d.cy=50;
d1.c x = 50; d1.cy = 100;
/*PROG 7.3 DEMO OF CLASS VER 5 */
import java.io.*;
import java.util.*;
class person
{
   private int age;
   private String name;
   void input()
   {
          Scanner sc = new Scanner(System.in);
          System.out.println("Enter the age of person");
          age = sc.nextInt();
          System.out.println("Enter the name");
          name = sc.next();
   }
   void show()
   {
          System.out.println("
++++++++++++++++++++++++++++");
          System.out.println("	Person Details");
          System.out.println("
************************");
          System.out.println("Name=" + name);
          System.out.println("Age=" + age);
   }
}
class JPS5
{
   public static void main(String args[])
   {
          person p = new person();
     System.out.println("

+*+*+*+*+*+*+*+*+*+*+*+*+");
          p.input();
          p.show();
     System.out.println("
+**+*+*+*+*+*+*+*+*+*+*+*+*");
   }
}

OUTPUT:

*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+
Enter the age of person
26
Enter the name
Hari
++++++++++++++++++++++++++++++++
             Person Details
********************************
Name=Hari
Age=26
+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*

Explanation: The program is similar to the previous program but instead of providing constant values to the data members of the class input is taken from the console. Note that, several examples of taking input from console have already been discussed in the earlier chapters.

/*PROG 7.4 READING AND WRITING STUDENT DATA */
import java.io.*;
import java.util.*;
class student{
   private String sname;
   private int sage;
   private String sclaass;
   void getdata(String sn, int sa, String sc)
   {
          sname = sn;
          sage = sa;
          sclass = sc;
   }
   void showdata()
   {
          System.out.println("Name :=	" + sname);
          System.out.println("Age :=	" + sage);
          System.out.println("Class:=	" + sclass);
   }
}
class JPS6{
   public static void main(String args[]){
          student s1, s2;
          String n, c;
          int a;
          Scanner sc = new Scanner(System.in);
          s1 = new student();
          s2 = new student();
          System.out.println("Enter data for student-1
");
          n = sc.next();
          a = sc.nextInt();
          c = sc.next();
          s1.getdata(n, a, c);
          System.out.println("Enter data for student-2
");
          n = sc.next();
          a = sc.nextInt();
          c = sc.next();
          s2.getdata(n, a, c);
          System.out.println("
========================");
          System.out.println("	STUDENT-1");
          System.out.println("========================
");
          s1.showdata();
          System.out.println("
+++++++++++++++++++++++");
          System.out.println("	STUDENT-2");
          System.out.println("************************
");
          s2.showdata();
          System.out.println("++++++++++++++++++++++++
");
}
}

OUTPUT:

Enter data for student-1
Hari 25 M.Tech(CSE)
Enter data for student-2
Ranjana 21 PGDCA
================================
          STUDENT-1
================================
Name := Hari
Age  := 25
Class:= M.Tech(CSE)
++++++++++++++++++++++++++++++++
          STUDENT-2
********************************
Name := Ranjana
Age  := 21
Class:= PGDCA
++++++++++++++++++++++++++++++++

Explanation: In the student class, there are three data members namely, sname, sage, sclass and two member functions. One function is for inputting the data and another for displaying the data. In the main, two objects s1 and s2 are created. Two separate memory blocks for data members for each of the objects s1 and s2 are allocated and both have their different copy of each data members. We input values for these data members in local variables and call functions getdata and showdata for both the objects.

7.3 ACCESSING PRIVATE DATA

Data is declared as private so that it is only accessible inside the functions of the class and other external functions cannot use the private data. But sometimes it is required that the private data is accessible outside the class and for this, the one way is to make them public, but this defies the principle of data hiding. The other solution is to create public member functions that return the private data members. This is the way which is usually employed for accessing private data. Similarly, for private data one can have private member functions. But private member functions can be used only inside the other member functions of the class as they cannot be called from outside the class.

The following example is given to understand how to access private data.

/*PROG 7.5 ACCESSING PRIVATE DATA OUTSIDE THE CLASS VER 1*/
import java.io.*;
import java.util.*;
class demo {
   private int num;
   void fun()
   {
          num = 30;
   }
   int getnum()
   {
          return num;
   }
}
class JPS8
{
   public static void main(String args[])
   {
          demo d = new demo();
          d.fun();
          System.out.println("Num is:= " + d.getnum());
   }
}

OUTPUT:

Num is:= 30

Explanation: In the program, a class demo has a private data member num . In the main , when function fun is called by an object d of class demo , the num is initialized to 30 . In order to access this value of num outside the class, a public member function getnum() is written which returns the value of num . As the type of num is int the written type of function getnum is kept as int . In the main when this function is called as d.getnum() num is returned from the function getnum . Thus, private data member has been accessed outside the class.

/*PROG 7.6 ACCESSING PRIVATE DATA OUTSIDE THE CLASS VER 2 */
class Person {
{
   private String name;
   private char sex;
   private float sal;
   void input(String n, char s, float f)
   {
          name = n;
          sex = s;
          sal = f;
   }
   String getname()
   {
          return name;
   }
   char getsex()
   {
          return sex;
   }
   float getsal()
   {
          return sal;
   }
}
class JPS8
{
   public static void main(String[]args)
   {
          Person p = new Person();
          p.input("Vijay Nath", 'M', 30000f);
          System.out.println("Name :="+p.getname());
          System.out.println("Sex :="+p.getsex());
          System.out.println("Salary :="+p.getsal());
   }
}

OUTPUT:

Name   :=Vijay Nath
Sex    :=M
Salary :=30000.0

Explanation: In this program, for accessing the name of the private data members and also their sex and salary, three public member functions-getname, getsex and getsal-are written which return the value of name, sex and sal, respectively. Note that depending on the type of data member that is returned from public member functions, the return type is set accordingly.

/*PROG 7.7 WORKING WITH MORE THAN ONE OBJECTS */
class Emp
{
   private String ename;
   private float sal;
   void input(String n, float s)
   {
          ename = n;
          sal = s;
   }
   float getsal()
   {
          return sal;
   }
   String getname()
   {
          return ename;
   }
};
class JPS10
{
   public static void main(String args[])
   {
          Emp e1 = new Emp();
          e1.input("Hari", 25000);
          Emp e2 = new Emp();
          e2.input("Juhi", 20000);
          if (e1.getsal() > e2.getsal())
          System.out.println("

"+e1.getname()+" 's
                                       salary is higher");
        else
          System.out.println("

"+e2.getname() + " 's
                                       salary is higher");
      }
}

OUTPUT:

Hari 's salary is higher

Explanation: The class Emp has two data fields: ename and sal . In the main, two objects are created and the values to the data members assigned using input method. The class has two public methods which return the values ename and sal of the private field. In the main, salary of the two Emp objects is compared and appropriate message is displayed.

7.4 PASSING AND RETURNING OBJECTS

Similar to returning and passing arguments to functions of basic types like int, char, double, float, and char*, one can pass objects of class to function and even return objects from functions. In order to pass objects, one has to simply write in the declaration of function, the class name whose objects will be passed. Similarly, for returning an object, the class name has to be written as return type. For example, for a function show which takes an object of demo class type and returns an object of demo class, the following declaration is written:

demo show (demo);

One important thing to note while passing the objects to functions is that objects are never passed to the functions as value. They are always passed by reference, i.e., no new object is created and instead, a new reference is created which points to previously existing object whose reference is passed to the method.

/*PROG 7.8 PASSING OBJECT TO METHOD */ class demo
class demo
{
   private int num;
   void input(int x)
   {
          num = x;
   }
   void twice(demo d)
   {
          num = 2 * d.num;
   }
   void show()
   {
          System.out.println("num:=" + num);
   }

}
class JPS11
{
   public static void main(String args[])
   {
          demo d1 = new demo();
          demo d2 = new demo();
          d1.input(50);
          d2.twice(d1);
          System.out.println("Object d1");
          d1.show();
          System.out.println("Object d2");
          d2.show();
   }
}

OUTPUT:

Object d1
num: =50
Object d2
num: =100

Explanation: The method twice receives an object of the class demo type. In the main, two objects d1 and d2 are created and a value of 50 to num of d1 is assigned using input method. In the next line d2.twice (d1), d2 calls the method twice and sends d1 as argument. Inside the method, twice reference of d1 is assigned to d . Now both d and d1 starts pointing to the same object. Any changes made inside twice on num data members by d are reflected back in d1. Inside the method twice num represents num of object d2 which gets double the value of d.num (actually d1.num). Later on, the value of num for both the objects is displayed.

Now, the function is changed twice as given below.

void twice(demo d)
{
   num = 2 * d.num;
   d.num = 1000;
}

When a function is called as d2.twice (d1); the reference of d1 is passed to the method twice. This reference is stored in the d . Now, both d and d1 refer to the same object and therefore any changes performed using either of the references d or d1 actually occur on to the same object. Inside the method, the value of d.num changes to 1000 . In the main when the value of d1.num is printed the same value is obtained.

/*PROG 7.9 RETURNING OBJECT FROM METHOD */
class demo {
{
   private int num;
   void input(int x)
   {
        num = x;
   }
   demo twice()
   {
        demo temp = new demo();
        temp.num = 2 * num;
        return temp;
   }
   void show()
   {
        System.out.println("num:= " + num);
   }
}
class JPS13
{
   public static void main(String args[])
   {
          demo d1 = new demo();
          demo d2 = new demo();
          d1.input(50);
          d2 = d1.twice();
          System.out.println("Object d1");
          d1.show();
          System.out.println("Object d2");
          d2.show();
   }
}

OUTPUT:

Object d1
num: = 50
Object d2
num: = 100

Explanation: The declaration demo twice () tells the compiler that the function twice does not take any argument and returns an object of the type demo . Note how the function is defined as given below.

In the line demo twice (), the demo is the return type and twice specifies that it is a function. Inside the function, a temporary object temp is created. Inside this object temp num data member, 2*num of object d1; is assigned. Actually, this is the object which called the function twice in the main as d2 5 d1.twice() . When the function twice returns the object temp, it is assigned to d2 as d2 5 temp which copies num of temp to num of d2.

/*PROG 7.10 SUM OF TWO TIME DURATION */
class time
{
   private int hours;
   private int minutes;
   private int secs;
   void input_time(int hh, int mm, int ss)
   {
          hours = hh;
          minutes = mm;
          secs = ss;
   }
   time sum_time(time A, time B)
   {
          int h, m, s;
          time temp = new time();
          s = A.secs + B.secs;
          m = A.minutes + B.minutes + s / 60;
          h = A.hours + B.hours + m / 60;
          temp.secs = s % 60;
          temp.minutes = m % 60;
          temp.hours = h;
          return temp;
   }
   void show_time(String str)
   {
          System.out.println(str);
          System.out.print("Hours = " + hours + "	");
          System.out.print("Minutes = " + minutes + "	");
          System.out.println("Seconds=" + secs);
   }
};
class JPS14
{
   public static void main(String args[])
   {
          time time1, time2, time3;
          time1 = new time();
          time2 = new time();
          time3 = new time();
          time1.input_time(3, 34, 45);
          time2.input_time(4, 26, 55);
          time3 = time3.sum_time(time1, time2);
          System.out.println("

++++++++++++++++++++++");
          time1.show_time("
	Time 1");
          System.out.println("**************************");
          time2.show_time("
	Time 2");
          System.out.println("++++++++++++++++++++++++++");
          time3.show_time("Sum of two duration is ");
          System.out.println("**********************

");
      }
}

OUTPUT:

+++++++++++++++++++++++++++++++++++++++++++++
             Time 1
Hours = 3 Minutes = 34 Seconds=45
*********************************************
             Time 2
Hours = 4 Minutes = 26 Seconds=55
+++++++++++++++++++++++++++++++++++++++++++++
Sum of two duration is
Hours = 8 Minutes = 1 Seconds=40
*********************************************

Explanation: In the program, the sum of two time durations is found. The function declaration time sum_ time (time A, time B) tells the compiler that sum_time is a function which takes two arguments (objects) of the class time type and return an argument (object) of the class time type. In the main, hours, minutes and seconds of two objects of the data members are initialized, i.e., time1 and time2 by calling the function input_time. In the statement,

time3 = time3.sum_time(time1, time2);

time3 calls the function sum_time and passes time1 and time2 as argument. Inside the function sum_time, the number of seconds, minutes and hours is first calculated in local variables- s, m and h -and from them values to data members of temp objects are actually assigned. In the end, this temp object is returned and assigned to time3 in the main.

7.5 COPYING OBJECTS

In Java, two objects cannot be copied directly by writing simply the assignment as d1 = d2; e.g., for copying object d2 to d1 . In Java, when d2 = d1 is written, it means reference d1 is assigned to d2. That is, d2 gets the reference of d1 and both points to the same object and both will be sharing the same data members. The changes done by one will be reflected to the other.

Consider the following code:

class demo
{
      public int num;
      void change()
      {
             num = 500;
      }
}
demo A=new demo();
demo B=new demo();
A.num=100;
B=A;
A.change();
System.out.println("After returning from function");
System.out.println("B.num:="+B.num+"	A.num:="+A.num);

Initially, the value of num for object A is 100 . In the statement B = A, all the members of A are not copied to B and instead B is getting a reference to A . This means, whatever A was referring, B will start referring the same object. After the statement B = A, both A and B are the two references for one object. The changes made through either of the references A or B are reflected to the object. The method change is called through the reference A . Inside the method change value of num changes to 500 . Later on, when the value of num is printed using A and B, the same value is obtained. The same is the case when the objects are passed to methods. In Java, the objects to methods are always passed by the references as stated earlier.

/*PROG 7.11 DEMO OF COPYING OBEJCTS VER 1, DOES NOT WORK */
import java.io.*;
import java.util.*;
class demo
{
   private String sname;
   void show()
   {
          System.out.println("Name=" + sname);
   }
   void change()
   {
          sname = "Changed TO Pandey";
   }
   void input()
   {
          Scanner sc = new Scanner(System.in);
          System.out.println("Enter the name");
          sname = sc.next();
   }
}
class JPS15
{
   public static void main(String args[])
   {
          demo d1 = new demo();
          demo d2;
          d1.input();
          d1.show();
          d2 = d1;
          d2.change();
          d1.show();
   }

}

OUTPUT:

Enter the name
HARI
Name=HARI
Name=Changed TO Pandey

Explanation: In the program, the object d1 is created and initialized. Assume that the string entered for the data member sname is 'HARI'. In the statement demo d2, only a reference of the demo class is created. Next d2 = d1 causes d2 to get the reference of d1. Now, both d1 and d2 start pointing to the same object of the demo class. This is as shown in Figure 7.2 (a-b).

images

Figure 7.2 (a) Before d2 = d1; (b) After d2 = d1

Note that in the program after d2 = d1, the change function is called using d2 as reference which changes the contents of sname from 'HARI' to 'Change To Pandey'. Next, when the sname is displayed by a call to show using d1, the same changed name is displayed. In order to really copy the data members, either the object has to be passed to the methods or return objects from the methods. An approach is shown in the next program.

/*PROG 7.12 DEMO OF COPYING OBJECTS VER 2, DOES WORK */
import java.io.*;
class person
{
   protected String sname;
   protected int age;
   protected String profession;
   void show()
   {
          System.out.println("Name ="+sname);
          System.out.println("Age ="+age);
          System.out.println("Profession ="+profession);
   }
   person copy()
   {
          person temp=new person();
          temp.sname=sname;
          temp.age=age;
          temp.profession=profession;
          return temp;
   }
   void input(String sn, int a, String p)
   {
          sname=sn;
          age=a;
          profession=p;
   }
}
class JPS16
{
   public static void main(String args[])
   {
          person p1 = new person();
          person p2;
          p1.input("Saurabh", 20, "Student");
          p2 = p1.copy();
          System.out.println("Person 1");
          p1.show();
          System.out.println("Person 2");
          p2.show();
   }
}

OUTPUT:

Person 1
Name =Saurabh
Age =20
Profession =Student
Person 2
Name =Saurabh
Age =20
Profession =Student

Explanation: The method copy when called creates a new temporary object and copies all the members of the object who actually called the method. In the end, this object is returned and assigned to p2.

7.6 ARRAY OF OBJECTS

Similar to the array of any basic data types an array of objects of any class can be created. This becomes handy when one wants to process something like the salary of a number of employees, accounts of persons, records of students, etc. In all these situations, an array of objects makes the work and processing easier and faster. In Java, each object of an array must be initialized first before it can be used. For a class demo, an array of objects can be created as demo [] = new demo [5];

The above line creates an array of object of size 5. But in reality, it is an array of references of class demo type and not an array of objects until they are initialized in the following way:

for(int i=0; i<arr.length;i++)
arr[i] = new demo ();

After initializing, the first array of object is referred to as arr[0], second as arr[1] and so on. The data members and methods of objects can be accessed as arr[i].datamembers and arr[i]. methodname where 'i' is a valid index.

/*PROG 7.13 DEMO OF ARRAY OF OBJECT VER 1*/
import java.io.*;
import java.util.*;
class Point
{
   private int px;
   private int py;
   void input(int x, int y)
   {
          px = x;
          py = y;
   }
   void show()
   {
          System.out.println("(" + px + "," + py + ")");
   }
}
class JPS17
{
   public static void main(String args[])
   {
          Point ptarr[]=new Point[5];
          int i;
          System.out.println("Points are");
          for(i=0;i<ptarr.length;i++)
          {
                 ptarr[i]=new Point();
                 ptarr[i].input(234+i*2,254+i*3);
                 ptarr[i].show();
          }
   }
}

OUTPUT:

Points are
(234,254)
(236,257)
(238,260)
(240,263)
(242,266)

Explanation: The class Point store x and y coordinates of a point. Inside the main, an array ptarr of size 5 of class type Point is created. This is similar to creating 5 objects with different name. The array ptarr is an object array of class Point type. The ptarr[0] denotes the first object, ptarr[1] the second and so on. In the main, input function for all the objects is called using the for loop and pass arbitrary points to function. Each object will be having different points as data members for each object are unique. The points of each object are displayed using show inside the for loop.

/*PROG 7.14 MERIT LIST OF STUDENTS */
import java.io.*;
import java.util.*;
class student
{
   private String sname;
   private int m1, m2, m3;
   private float per;
   void input()
   {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the stduent name");
        sname = sc.next();
        System.out.println("Enter the marks in subject-1");
        m1 = sc.nextInt();
        System.out.println("Enter the marks in subject-2");
        m2 = sc.nextInt();
        System.out.println("Enter the marks in subject-3");
        m3 = sc.nextInt();
        per = (m1 + m2 + m3) / 3.0f;
   }
   void show()
   {
        System.out.println(sname + "	" + per);
   }
   float getper()
   {
        return per;
   }
}
class JPS19
{
   public static void main(String args[])
   {
        final int s = 3;
        student[] sarr = new student[s];
        int i, j;
        student temp = new student();
        for (i = 0; i < s; i++)
        {
              sarr[i] = new student();
              sarr[i].input();
        }
        for (i = 0; i < s; i++)
              for (j = i + 1; j < s; j++)
              if (sarr[i].getper() < sarr[j].getper())
                    {
                           temp = sarr[i];
                           sarr[i] = sarr[j];
                           sarr[j] = temp;
                    }
        System.out.println("Student Merit List
");
        System.out.println("
NAME 	Per(%)
");
        for (i = 0; i < s; i++)
               sarr[i].show();
   }
}
OUTPUT:
Enter the stduent name
Hari
Enter the marks in subject-1
60
Enter the marks in subject-2
80
Enter the marks in subject-3
85
Enter the stduent name
Man
Enter the marks in subject-1
76
Enter the marks in subject-2
87
Enter the marks in subject-3
69
Enter the stduent name
Ruchika
Enter the marks in subject-1
60
Enter the marks in subject-2
78
Enter the marks in subject-3
90
Student Merit List
NAME Per(%)
Man 77.333336
Ruchika 76.0
Hari 75.0

Explanation: The class student has 5 data members: name, m1, m2, m3 and per. For storing marks in three subjects there are m1 , m2 and m3 . The per is for storing percentage and the sname is for storing name. It is assumed that all marks are from 100 (though no checking has been done through it). In the function input, after marking, the percentage is found and stored in per. In the main, sorting is performed on the basis of percentage as the merit list of the students needs to be generated. As per is private, we have made a public member function getper which returns per in the main sorting is done on this function getper basis. Note that the whole object has been swapped while sorting is being done. For this purpose, a temporary object temp is taken and subsequently the merit list is displayed using show and for loop.

7.7 STATIC CLASS MEMBERS

Static variables are those which persist even after the control returns from the function. In terms of static members as class members, they are the members for a class and not for an object. Static data members are needed when only one piece of storage is needed for a particular piece of data, regardless of how many objects are created or even if no objects are created. static method is not associated with any particular object of this class. This means that it is a method that one can call even if no objects are created. One such method is the main method of all Java programs.

It is known that the functions of a class are defined only once and they can be called by an object of the class, but static functions are those functions which belong to the class only. Static members can be either functions or static data. Static data members (field + method) are sometimes known as class variables or class methods as they belong to whole of the class.

7.7.1 Static Member Functions

The various points about the static member functions are as follows:

1.   Static functions are those which are made static by placing the keyword static before the function definition inside the class.

2.   Static functions are one for class and can be called as

If demo is the class name and stat is the static function name then it can be called as demo.sat().

3.   In a static function, only the static data members, other static variables or other static functions can be used.

4.   Although a static member function is called using a class name, it can be called explicitly using the object of the class.

5.   Inside the static methods, only the static data and methods can be used, but a static method can be called from a non-static method.

In the previous chapter, several examples of static method were given but not in detail. So a few practical programs with their explanation are given below.

/*PROG 7.15 DEMO OF STATIC METHOD */ class demo
class demo
{
   static void show()
   {
          System.out.println("Welcome from static show");
   }
}
class JPS20
{
   public static void main(String args[])
   {
          demo d = new demo();
          d.show();
          demo.show();
          (new demo()).show();
   }
}

OUTPUT:

Welcome from static show
Welcome from static show
Welcome from static show

Explanation: A static method can be called from using an object of the class or using a class itself. Both the ways have been demonstrated in the above program. As new demo() creates an object, the last line in the main is also a correct way for calling a static method.

/*PROG 7.16 CALLING A STATIC METHOD FROM A NON STATIC METHOD */
class demo{
   static void show()
   {
      System.out.println("

Hello from static show");
   }
   void display()
   {
      System.out.println("
Hello from non static
display");
      show();
   }
}
class JPS21
{
      public static void main(String args[])
      {
           demo d1 = new demo();
           d1.display();
      }
}
OUTPUT:

Hello from non static display
Hello from static show

7.7.2 Static Data Members

It is known that whenever an object is created, separate copies of data members are created for each object. But in the case of static data members, only one copy of static data members is available which is shared among all the objects created. The various points about the static data members are as follows:

1.   They are created by placing the static keyword before variable declaration.

2.   All static variables get their default initial value as 0 when the first object of a class is created.

3.   A single copy of the static data member is created which is shared among all objects. The changes made by one object on a static data member are reflected back to all other objects.

4.   The lifetime of a static variable is the entire program.

5.   They are used when one value common to the whole class is kept.

6.   They can be accessed either by object name or by class name.

As an example of static member consider the code given below.

class demo
{
static int num = 100;
}
demo d=new demo();
System.out.println(demo.num++); //prints 100
System.out.println(++d.num); //prints 101

In this code, the static member num is accessed, once using a class and then using an object. As only one copy of num is available, the value of num increments twice.

Consider another example.

class demo
{
static int s;
int ns;
};
demo d1=new demo();
demo d2=new demo();
demo d3=new demo();

Assume value of s is 1 and values of ns for d1, d2 and d3 are 10, 20, and 30, respectively (Figure 7.3).

images

Figure 7.3 Implementation of static data number

One for class, common to all objects

/*PROG 7.17 WORKING WITH STATIC AND NON STATIC DATA */
class demo
{
   static int snum = 20;
   int ns;
}
class JPS22
{
   public static void main(String args[])
   {
          demo d1 = new demo();
          d1.ns = 50;
          d1.snum++;
          demo d2 = new demo();
          d2.ns = 100;
          d2.snum++;
          System.out.println("
ns of d1=" + d1.ns);
          System.out.println("
ns of d2=" + d2.ns);
          System.out.println("
Static snum=" + demo.snum);
   }
}

OUTPUT:

ns of d1=50
ns of d2=100
Static snum=22

Explanation: The data member snum is static and so only one copy of it will be shared among all the objects created. But 'ns ' is non-static and so for all objects of demo class a separate copy of ns will be available.

7.8 CONSTRUCTORS

A constructor is a special member function whose name is the same as the name of its class in which it is declared and defined. The purpose of the constructor is to initialize the objects of the class. The constructor is called so because it is used to construct the objects of the class. The constructor is used to construct the object at run time. A default constructor ('no-arg' constructor) is one without arguments that is used to create a class which has no constructor and the compiler will automatically create a default constructor which has been seen in all other programs where it has been created by writing new classname();

A small example of the constructor is given below.

class demo
{
         demo()
         {
            System.out.println("Hello from constructor");
         }
}
class JPS
{
         public static void main(String args[])
         {
                demo d = new demo();
         }
}

OUTPUT:

     Hello from constructor

The name of the class is demo and the following function definition is

demo()
{
 System.out.println("Hello from constructor");
}

a constructor of the class as the name of the function is the name of the class. The various features of the constructor are as follows:

1.   The constructor invokes automatically when objects of the class are created. The declaration new demo(); creates an object which automatically calls the constructor of the class and prints 'Hello from constructor'.

2.   The constructors are always public. If declared private then the objects can only be created inside the member functions, which serve no purpose.

3.   The constructors are used to construct the objects of the class.

4.   The constructor does not have any return type, not even void and therefore, it cannot return any value.

5.   The constructor with no argument is known as default constructor of the class. The default constructor for the class demo will be demo()

6.   The constructor that takes arguments like a function takes are known as parameterized constructors.

7.   There is no limit of the number of constructors declared in a class but all must conform to rules of function overloading.

In the other programs discussed earlier, the objects were created using the constructor but no constructor in the program was created. Note that behind every object creation, a constructor is required. Then who was creating the objects in all these programs where the classes and objects were made use of? The answer is simple: When no constructor is created in the class, the compiler provides the default constructor for the class and that constructor is known as default constructor or do-nothing constructor. The sole purpose of this constructor is to construct the objects for the class.

/*PROG 7.18 CONSTRUCTOR RETURNING VALUES */
class demo
{
   demo()
   {
   System.out.println("Hello from constructor");
   }
   void demo()
   {
          System.out.println("Hello from function ");
   }
}
class JPS23
{
          public static void main(String args[])
   {
          demo d = new demo();
          d.demo();
   }
}

OUTPUT:

Hello from constructor
Hello from function

Explanation: In Java, the constructor can return values but they are not treated as constructor. They are treated as functions. Here void demo() is a function which returns nothing. In the main, d.demo() calls this function.

7.8.1 Constructors with Parameters

The constructors are similar to functions but they have the name as class name. Therefore, similar to functions, which takes arguments, one can also have constructors which can take arguments. The constructor which takes parameters is known as parameterized constructor. Depending on the type and number of arguments they may be overloaded. Again, when parameterized constructor and objects like new demo() assume demo is the class name are created, a compilation error will be generated. This is because whenever any type of constructor is created, the compiler does not provide one with the default constructor. It forces the programmer to create all such constructors which can build the object.

An example of this fact is given below.

/*PROG 7.19 DEMO OF PARAMETERIZED CONSTRUCTOR VER 1 */ class demo
class demo
{
   demo()
   {
         System.out.println("
Zero Argument Constructor");
   }
   demo(int x)
   {
         System.out.println("
 One Argument Constructor");
   }
   demo(int x, int y)
   {
         System.out.println("
 Two Argument Constructor");
   }
}
class JPS24
{
   public static void main(String args[])
   {
          demo d = new demo();
          d = new demo(1);
          d = new demo(1, 2);
   }
}

OUTPUT:

Zero Argument Constructor
One Argument Constructor
Two Argument Constructor

Explanation: The first line in the main calls default constructor for the class. In the next line, the one argument constructor is called due to new demo (1). In the next line, new demo (1, 2) calls the two argument constructor. Note that in all the three lines in the main the same reference has been used. The same can also be written in the following manner:

demo d = new demo();
demo d1 = new demo(1);
demo d2 = new demo(1, 2);
/*PROG 7.20 INTIALIZEING STRING DATA */
class demo
{
   private String str;
   demo()
   {
          System.out.println("

Hello from constructor");
          str = "Welcome in NMIMS";
   }
   demo(String s)
   {
          str = s;
   }
   void show(String s)
   {
         System.out.println(s);
         System.out.println("
String is " + str);
   }
}
class JPS26
{
   public static void main(String args[])
   {
         demo d;
         d = new demo();
         d.show("Object d");
         demo d1;
         d1 = new demo("Cutie Pie");
         d1.show("Object d1");
   }
}

OUTPUT:

Hello from constructor
Object d
String is Welcome in NMIMS
Object d1
String is Cutie Pie

Explanation: When the default constructor for object d is called String data member str is initialized to 'Welcome in NMIMS' . When an argument constructor taking a String argument is called 'Cutie Pie' is assigned to str of object d1 and the previous String data is lost.

/*PROG 7.21 CONSTRUCTOR WITH ARRAY OF OBJECT */ class demo
class demo
{
   demo()
   {
          System.out.println("
Hello from constructor ");
   }
}
class JPS27
{
   public static void main(String args[])
   {
          demo[] d = new demo[5];
          for (int i = 0; i < d.length; i++)
            d[i] = new demo();
   }
}
OUTPUT:
Hello from constructor
Hello from constructor
Hello from constructor
Hello from constructor
Hello from constructor

Explanation: The important thing to note here is that the default constructor is not called when demo[]d = new demo [5]; executes. It is called when d[i] = new demo(); executes.

/*PROG 7.22 SEPARATING FLOAT AND INT PART */
class convert
{
   private double num;
   private int intp;
   private double realp;
   convert()
   { }
   convert(double n)
   {
          num = n;
   }
   void find()
   {
          intp = (int)(num);
          realp = num - intp;
          show();
   }
   void show()
   {
          System.out.println("Number =" + num);
          System.out.println("Integer Part =" + intp);
          System.out.println("Real Part =" + realp);
   }
};
class JPS28
{
   public static void main(String args[])
   {
          convert A = new convert(34.56);
          convert B;
          B = new convert(234.67);
          System.out.println("
************************");
          System.out.println("	First Object
");
          System.out.println("**************************");
          A.find();
          System.out.println("
************************");
          System.out.println("	
Second Object
");
          System.out.println("**************************");
          B.find();
      }
}

OUTPUT:

*********************************
      First Object
**********************************
Number =34.56
Integer Part =34
Real Part =0.5600000000000023
********************************
      Second Object
*********************************
Number =234.67
Integer Part =234
Real Part =0.6699999999999875

Explanation: The program is simple. First, the number num is converted into int by typecasting and stored in intp. It is then subtracted from the original number num to find out the real part.

In the program, the constructor convert(){} serves as empty/default/zero argument constructor. The default constructor serves nothing special here as it is having an empty body. This constructor can be used to provide the initial values to the members of the objects of the class. As a one argument constructor has been created the constructor can be called by writing convert c1 = new convert ("34.36"), but if it is written otherwise, it should be in the following way:

convert c1;
c1= convert("34.56");

Again, there must be a default constructor as stated in the above paragraph. If the object is not created by writing convert c1; there is no need to create the default constructor or empty constructor. But once the statement convert c1; is written there must be an empty constructor in the program. This is a must as in case of no constructor in the class, Java provides its default implicit constructor to construct the objects. (Remember, where there is no constructor there is no object). Once we have made constructors in our class of any type and in any number and we create the object by writing convert c1 without creating a default constructor, the compiler flashes the error 'default constructor required'. This constructor is a do-nothing constructor and is used to just satisfy the compiler. Try running the program by commenting the default constructor in the program.

/*PROG 7.23 ADDITION AND SUBTRACTION OF TWO COMPLEX NUMBER */
class complex
{
   double real;
   double imag;
   complex()
   {
   real = imag = 0;
   }
   complex(double r, double i)
   {
         real = r;
         imag = i;
   }
   complex sum(complex A, complex B)
   {
         complex temp = new complex();
         temp.real = A.real + B.real;
         temp.imag = A.imag + B.real;
          return temp;
   }
   complex sub(complex A, complex B)
   {
          complex temp = new complex();
          temp.real = A.real - B.real;
          temp.imag = A.imag - B.imag;
          return temp;
   }
   void show()
   {
          System.out.println(real + "+j " + imag);
   }
}
class JPS29
{
   public static void main(String[] args)
   {
          complex c1 = new complex(2.0, 3.0);
          complex c2 = new complex(3.0, 2.0);
          complex c3 = new complex();
          complex c4 = new complex();
          c3 = c1.sum(c1, c2);
          c4 = c1.sub(c1, c2);
          System.out.print("

 C1 := ");
          c1.show();
          System.out.print(" C2 := ");
          c2.show();
          System.out.print(" SUM := ");
          c3.show();
          System.out.print(" SUB := ");
          c4.show();
   }
}

OUTPUT:

C1  := 2.0+j 3.0
C2  := 3.0+j 2.0
SUM := 5.0+j 6.0
SUB := -1.0+j 1.0

Explanation: In the program, there is one default constructor and the second constructor is with two parameters of type double. In order to find the addition and subtraction of two complex numbers, two functions sum and sub are written which takes two arguments of class complex type and return a value of class complex type. We also have another function show which displays the complex number. The class has two private data members, real and imag, which represents real and imaginary part of a complex number with the two statements.

complex c1 = new complex(2.0, 3.0);
complex c2 = new complex(3.0, 2.0);

We call the two arguments as constructors and set the real and imaginary part for objects c1 and c2 For finding the sum of c1 and c2, the function sum is called and c1 and c2 are passed as argument as c3 = c1.sum(c1,c2); In the function sum, two real parts and two imaginary parts are added separately and stored in a temporary array which is returned and assigned to c3. Similarly, subtraction is performed by a call to sub-function and subtraction of c1 and c2 is assigned to c4. Later on, they are displayed by a call to show.

/*PROG 7.24 STACK SIMULATION */
import java.io.*;
import java.util.*;
class stack
{
   private int top;
   private int st[];
   private final int S = 10;
   stack()
   {
          top = -1;
          st = new int[S];
   }
   void push(int item)
   {
          if (top == 9)
          {
                System.out.println("
Stack is full");
                System.exit(0);
          }
          st[++top] = item;
          System.out.println("
ITEM PUSHED");
   }
   int pop()
   {
          if (top == -1)
          {
                System.out.println("
Stack is empty");
                System.exit(0);
          }
          return st[top--];
   }
}
class JPS30
{
   public static void main(String[] args)
   {
          stack s = new stack();
          int ch, item;
          Scanner sc = new Scanner(System.in);
          do{
                 System.out.println("

Stack Simulation
                                        Demo
");
                 System.out.println("1. PUSH");
                 System.out.println("2. POP");
                 System.out.println("3. QUIT");
                 System.out.print("
Enter your choice:=");
                 ch = sc.nextInt();
                 switch (ch)
                 {
                    case 1:
                      System.out.print("
Enter the
                                          item:=");
                      item = sc.nextInt();
                      s.push(item);
                      break;
                    case 2:
                      item = s.pop();
                      System.out.println("
Item poped=
                                             " + item);
                      break;
                    case 3:
                    System.out.println("
BYE BYE!!!");
                       System.exit(0);
                       break;
                    default:
                    System.out.println("
ERROR!!!!!");
                         break;
                 }
          } while (ch <= 1 && ch <= 3);
      }
}

OUTPUT:

Stack Simulation Demo
1. PUSH
2. POP
3. QUIT
Enter your choice:=1
Enter the item:=12
ITEM PUSHED
Stack Simulation Demo
1. PUSH
2. POP
3. QUIT
Enter your choice:=2
Item poped=12
Stack Simulation Demo
1. PUSH
2. POP
3. QUIT
Enter your choice:=3
BYE BYE!!!
Stack Simulation Demo
1. PUSH
2. POP
3. QUIT
Enter your choice:=4
ERROR!!!!!

Explanation: The program is a simulating stack using an array. A stack is a data structure in which the last item inserted is taken out first. This being the reason they are known as LIFO (last in first out). Inserting an item in a stack is termed as push and taking an item out from the stack is termed as pop. Only one item can be pushed at a time which is added on to the top of the previous item pushed. Similarly, only one top most items can be popped back. For keeping track of the top item, a data member top is initialized to -1 when the object of the class stack is created. The program is simple: An array is taken as data member of class size 10 by the name st which is the stack. In order to push item into this stack st the top is incremented and item is assigned to st as st[top] = item. After each item is pushed, top is incremented. Before pushing an item, first it has to be checked whether there is a space for the new item in the stack. This is done in the following way:

if (top == 9)
{
       System.out.println("
Stack is full");
       System.exit(0);
}

If top = = 9, the stack is full and the program is terminated. When an item is popped, the value is taken at st[top] and the top is decremented by 1 and st[top--] is returned. Before popping an item, it is checked whether the stack is empty or not. This is done in the following way:

if (top == -1)
{
     System.out.println("
Stack is empty");
     System.exit(0);
}

If top is - 1, the stack is empty and the program is terminated. The diagrammatical representation of the stack operation is shown in Figure 7.4 (a-e).

images

Figure 7.4(a) Stack after push operation

images

Figure 7.4(b) Stack after push operation

images

Figure 7.4(c) Stack after push operation

images

Figure 7.4(d) Stack after pop operation

images

Figure 7.4(e) Stack after pop operation

/*PROG 7.25 QUEUE SIMULATION */
import java.io.*;
import java.util.*;
class queue
{
   private int front, rear;
   private int que[];
   private final int S=10;
   queue()
   {
          front = rear = -1;
          que = new int[S];
   }
   void insert (int item)
   {
          if(rear==S-1)
          {
               System.out.println("QUEUE IS FULL");
               System.exit(0);
          }
          if(front==-1)
          front =0;
          que[++rear]=item;
          System.out.println("ITEM INSERTED");
   }
   int del()
   {
          int item;
          if(front==-1)
          {
               System.out.println("QUEUE IS EMPTY");
               System.exit(0);
          }
          item=que[front];
          if(front==rear)
          front =rear =-1;
          else
          front++;
          return item;
   }
};
class JPS31
{
   public static void main(String args[])
   {
          queue q=new queue();
          int ch, item;
          Scanner sc= new Scanner(System.in);
          do
          {
                System.out.println("

QUEUE DEMO");
                System.out.println("1. INSERT");
                System.out.println("2. DELETE");
                System.out.println("3. QUIT");
                System.out.print("
Enter your choice:=");
                ch = sc.nextInt();
                switch(ch)
                {
                       case 1:
                        System.out.print("
Enter the
item");
                              item=sc.nextInt();
                              q.insert(item);
                              break;
                       case 2:
                              item=q.del();
                              System.out.println("Item
deleted:=
                                                         "+item);
                              break;
                       case 3:
                              System.out.println("BYE
BYE!!!");
                              System.exit(0);
                              break;
                       default:
                              System.out.
println("ERROR!!!!");
                      }
          }while(ch>=1&&ch*>=3);
   }
}

OUTPUT:

QUEUE DEMO
1. INSERT
2. DELETE
3. QUIT

Enter your choice:=1

Enter the item12
ITEM INSERTED
QUEUE DEMO
1. INSERT
2. DELETE
3. QUIT

Enter your choice:=2

Item deleted:=12
QUEUE DEMO
1. INSERT
2. DELETE
3. QUIT

Enter your choice:=3
BYE BYE!!!

Explanation: The program simulates the working of a queue using array and class. The queue is a data structure with two pointers: front and rear. Whenever a new item is added to the queue, a rear pointer is used. It is incremented by 1. If it is the first item inserted the front also becomes 1. The front pointer is used when an item is deleted from the queue and the front pointer is decremented by 1. If it is the last item in the queue, the front and rear are both equal to - 1. The queue is also known as FIFO (first in first out) as items are added always at the end of the queue (rear end) and are always deleted from front of the queue.

Initially, when the default constructor is called, the front and rear are initialized to - 1. For insertion of item into the queue (implemented as an array queue), the rear is incremented but it is also checked whether there is space for the element to be inserted:

if(rear==S-1)
{
       System.out.println("QUEUE IS FULL");
       System.exit(0);
}

If the item was the first item inserted front was - 1 earlier so it s made to 0. Item is inserted as que [++rear] = item. Pointer rear was also incremented.

For the deletion of item from the queue, the front pointer is used. The element in the queue at the front is returned as que [front]. Again, before deletion, it is checked whether the queue is empty or not in the following way:

if(front==-1)
{
       System.out.println("QUEUE IS EMPTY");
       System.exit(0);
}

Now, after deletion, if the front becomes equal to the rear (last item deleted) then both are assigned the value - 1 else front is incremented.

/*PROG 7.26 DYNAMIC ARRAY OF OBJECTS */
import java.io.*;
import java.util.*;
class demo{
   private int num;
   demo(int n){
          num = n;
   }
   void show(){
          System.out.println("	num :=" + num);
   }
}
class JPS32{
   public static void main(String[] args){
          demo d[] ={
                           new demo(15),
                           new demo(20),
                           new demo(35),
                           new demo(50),
                     };
          System.out.println("
************************");
          System.out.println("	Array elements are");
          System.out.println("
++++++++++++++++++++++++");
          for (int i = 0; i < d.length; i++)
          d[i].show();
   }
}

OUTPUT:

*************************************
          Array elements are
+++++++++++++++++++++++++++++++++++++
          num :=15
          num :=20
          num :=35
          num :=50

Explanation: Note how an array of objects is initialized.

demo d[] ={
                      new demo(15),
                      new demo(20),
                      new demo(35),
                      new demo(50),
          };

Each new demo(x) (x may any int value) creates an object in the array by calling one argument constructor and later on, the value of num is displayed for all objects using show

7.9 COPY CONSTRUCTOR

A copy constructor is a constructor in which a single object is passed as an argument. This is used to initialize an object from another object. Look at the statements given below.

demo d1= new demo();
demo d2= new demo(d1);

Note that the second statement makes a call to copy the constructor defined in the class. When there are two objects, say d1 and d2 and if d2 = d1 is written this results in copying only the reference d1 to d2 and after the assignment, both d1 and d2 refer to the same object. For a class demo copy, the constructor is written in the following way:

demo (demo d)
{
       //copy constructor code;
}
/*PROG 7.27 COPY CONSTRUCTOR IN JAVA */
class cheque
{
   boolean signed;
   cheque(boolean b)
   {
          signed = b;
   }
   cheque(cheque ch)
   {
          signed = ch.signed;
   }
   public void show()
   {
          if (signed)
            System.out.println("
Check has signed");
          else
            System.out.println("
Check has not signed");
   }
}
class JPS33
{
   public static void main(String args[])
   {
          cheque ch1 = new cheque(true);
          cheque ch2 = new cheque(ch1);
          ch1.show();
          ch1.signed = false;
          ch2.show();
          ch1.show();
   }
}

OUTPUT:

Check has signed
Check has signed
Check has not signed

Explanation: The code shown in bold is the copy constructor in Java. In the main, when the statement shown in bold executes, the copy constructor is called for ch2 and is passed as argument. The signed Boolean data members get the signed value of ch1 as the signed was having a true value for ch1 and also the signed value of ch2 will be having a true value too. In the main, the show was first called for ch1. This displays that the check has been signed. Next, the value of signed for object ch1 is changed to false and then show for ch1 and ch2 is called. The show for ch2 shows check has signed and show for ch1 shows check was not signed. Thus, the copy constructor has worked.

7.10 THE this REFERENCE

The this reference is a special built-in reference. It is a special keyword which holds the reference to the current object. This means that the current object can be referred using this reference anywhere in the class. The this reference can be used only inside the class, i.e., only inside the member functions of the class and cannot be used outside the class. The this reference is a constant reference. Suppose, there is a method fun of the class demo and d1 and d2 are its objects. The method fun takes just one argument of type integer. The call to fun with d1 and d2 is given below.

d1.fun(10);
d2.fun(20);

How does the method fun come to know whether it is being called for object d1 or object d2? Internally, in all function call the compiler sends through an object the first argument as reference of the object which is hidden from the programmer. Thus, the above two calls become something like the ones given below.

demo.fun(d1,10);
demo.fun(d2,20);

The above is done internally by the compiler. In order to have the reference to the current object inside the method, that reference can be used using this keyword as the object secretly passed can be used by using this. The this keyword, which can be used only inside a method, produces the reference to the object for which the method has been called for. This reference can be treated just like any other object reference. It must be kept in mind that a method is called from within another method of the class, which need not be used. The method is simply called. The current this reference is automatically used for the other method.

Some of the important points about this reference are as follows:

1.   It is an implicit reference used by the system.

2.   It stores the reference of the current object in context.

3.   It is a final reference to an object.

4.   It can only be used within non-static functions of the class.

5.   It is non-modifiable, and assignments to this are not allowed.

/*PROG 7.28 DEMO OF THIS REFERENCE VER 1 */
  class Mouse
{
   String cname;
   String type;
   float price;
   Mouse(String cname, String type, float price)
   {
          this.cname = cname;
          this.type = type;
          this.price = price;
          show();
   }
   void show()
   {
          System.out.println("
Company:=" + this.cname);
          System.out.println("
Type :=" + this.type);
          System.out.println("
Price :=" + this.price);
   }
}
class JPS34
{
   public static void main(String args[])
   {
          Mouse m = new Mouse("DELL", "Optical", 350.95f);
   }
}

OUTPUT:

Company     :=DELL
Type         :=Optical
Price        :=350.95

Explanation: In the main, the object m is the current object in context; so this reference stores the reference of object m. In the parameterized constructor for class Mouse, this.name, this.type and this. price refer to data fields of the current object m. They can also be written without this. But as the local parameters are having the same name as the fields of the class, this has to be used. Similarly, in show method this is not necessary.

/*PROG 7.29 RETURNING CURRENT OBJECT USING THIS */
class Game
{
   String pname;
   int points;
   Game(String pname, int points)
   {
          this.pname = pname;
          this.points = points;
   }
   void show()
   {
          System.out.print("Name := " + this.pname);
          System.out.println("	Points :=" + this.points);
          }
                 Game check(Game g)
          {
                 if (this.points > g.points)
                     return this;
                 else
                     return g;
          }
}
class JPS35
{
   public static void main(String args[])
   {
          Game g1 = new Game("Hari", 1560);
          Game g2 = new Game("Man", 1665);
          System.out.println("
++++++++++++++++++++++++");
          System.out.println("	Player-1");
          System.out.println("**************************");
          g1.show();
          System.out.println("
************************");
          System.out.println("	Player-2");
          System.out.println("++++++++++++++++++++++++++");
          g2.show();
          Game winner;
          winner = g1.check(g2);
          System.out.print("
 Winner is " + winner.pname);
          System.out.println(" with "+winner.points+"
          points");
   }
}

OUTPUT:

+++++++++++++++++++++++++++++++++
      Player-1
*********************************
      Name := Hari Points :=1560
*********************************
      Player-2
+++++++++++++++++++++++++++++++++
      Name := Man Points :=1665
      Winner is Man with 1665 points

Explanation: The class Game has two fields: pname and points . Using the parameterized constructor of class Game, the data members of the class are initialized for objects g1 and g2 . The method check takes an object and returns another object. This method checks and declares who is the winner by comparing the points of two players: g1 and g2. The object g1 cannot be returned from the method as it is not available in the method check. But it is a fact that this reference stores the reference of the current object in context. So this reference inside check method represents g1. The returned reference is assigned to the winner in the main and the result is displayed.

/*PROG 7.30 METHOD RETURNING THIS REFERENCE */
class demo
{
   int num;
   demo(int num)
   {
         this.num=num;
   }
   void show()
   {
         System.out.println("num :="+this.num);
   }
   demo incr()
   {
         num++;
         return this;
   }
}
class JPS36
{
   public static void main(String args[])
   {
         demo d1 = new demo(10);
         System.out.println("
Call incr() three times");
         d1.incr().incr().incr().show();
   }
}
OUTPUT:
Call incr() three times
num :=13

Explanation: The method incr returns a reference to the current object. In the main when d1.incr is called, num is incremented to 11 and the reference of the current object is returned which again call incr . This is done for three times and so num becomes 13. In the end, show is called which displays the num = 13.

/*PROG 7.31 THIS REFERENCE FOR CALLING CONSTRUCTOR FROM CONSTRUCTOR */
class demo{
   String str;
   int num;
   demo(String s) {
          str=s;
          System.out.println("Constructor with string
                              argument");
   }
   demo(int x)
   {
          num=x;
          System.out.println("Consturctor with int
                       argument");
   }
          demo(String str, int num){
          this(str);
          this.num=num;
          System.out.println("Constructor with string & int
          argument");
   }
          demo(){
          this("Default", 235);
          System.out.println("Constructor with default
          argument");
   }
   void show()
   {
          System.out.println("Str :="+str+"	num
          :="+this.num);
   }
}
class JPS37
{
  public static void main(String arg[])
  {
          demo d1 = new demo();
          d1.show();
          d1 = new demo(20);
          d1.show();
          d1 = new demo("fun");
          d1.show();
          d1 = new demo("welcome", 345);
          d1.show();
   }
}

OUTPUT:

Constructor with string argument
Constructor with string & int argument
Constructor with default argument
Str :=Default num :=235
Consturctor with int argument
Str :=null num :=20
Constructor with string argument
Str :=fun num :=0
Constructor with string argument
Constructor with string & int argument
Str :=welcome num :=345

Explanation: The line in bold shows that this can be used to call the constructor within the constructor with arguments. Follow the program step by step and the output will be obtained as shown above.

7.11 GARBAGE COLLECTION AND FINALIZE METHOD

In computer science, garbage collection (also known as GC) is a form of automatic memory management. The garbage collector attempts to reclaim garbage or memory used by objects that can never be accessed or mutated again by the application. Garbage collection was invented by John McCarthy around 1959 to solve the problem of manual memory management in his Lisp programming language.

Java has the garbage collector to reclaim the memory of objects that are no longer used. This garbage collection is done automatically in Java without the user intervention. In Java, sometimes one may require to do some clean-up work. For this purpose, one can override the finalize method whose prototype is given as follows:

protected void finalize()throws Throwable

The finalize method is called by the garbage collector on an object when the garbage collection determines that there are no more references to the object. When the garbage collector is ready to release the storage used for the object, it will first call finalize() and only when the next garbage collection passes, it will reclaim the memory of the object. So, if finalize(), is chosen to be used it gives the ability to perform some important clean-up at the time of garbage collection.

In Java, an object is not always garbage collected which means that there is no guarantee that finalize will be called.

7.12 THE FINAL KEYWORD REVISITED

The final keyword was discussed in the first chapter for declaring constants. It can also be used with object references rather than with primitive data types. With a primitive, final makes the value a constant but with an object reference, final makes the reference a constant. Once the reference is initialized to an object, it can never be changed to point out another object. However, the object itself can be modified. See the code given in the program below.

/*PROG 7.32 DEMO OF FINAL REFERENCE */
class demo
{
   String str;
   final int num=20;
   static final float PI=3.14f;
   demo(String s)
   {
          str=s;
   }
}
class JPS38
{
   public static void main(String args[])
   {
          final demo d = new demo("fun1");
          demo d1 = new demo("fun2");
          d = d1;
          d = new demo("Changed");
   }
}

OUTPUT:

COMPILATION ERROR

images

Figure 7.5 Error during the compilation of Program 7.32

The program gives the compilation error. The object reference d is a constant which cannot take reference of any other object. So the lines showed in bold are responsible for flashing the compilation errors. Also note that the member fields can be declared as constant and initialized so that their values are known as compile time.

7.12.1 Blank Finals

Java allows the creation of blank finals, which are fields that are declared as final but are not given an initialization value. The blank final must be initialized before it is used. However, blank finals provide more flexibility in the use of the final keywords; for example, a final field inside a class can now be different for each object and yet nobody can modify it.

class demo
{
        final int blank_final;
        demo(int num)
        {
              blank_final = num;
        }
}

In the main, the following can be written:

demo d1=new demo(20);  //blank_final is 20 for object d1
                       //and is a constant
demo d2=new demo(40);  //blank_final is 40 for object d2
                       //and is a constant

7.12.2 Final Arguments to Methods

Arguments can be passed to methods and ensured that they are not modified inside it. An example is given below.

class demo
{
       String str;
       demo(final String s)
       {
              str = s;
              s = "hello"; //can't modify a final argument
       }
}
class Temp
{
       public static void main(String[] args)
       {
              demo d = new demo("Can't Change Me");
       }
}

String s is final in the constructor demo and so it cannot be modified.

7.13 PONDERABLE POINTS

1.   In Java, all objects are created dynamically by the new operator.

2.   All functions and methods must be a part of the class. One cannot declare methods inside the class and define them outside the class.

3.   For declaring a method or field as private, protected or public, each field or method must be individually tagged with a visibility modifier.

4.   In Java, a protected member cannot be accessed outside the class.

5.   In Java, a constructor can act as a function and can return value.

6.   The base/root class of all Java classes is the object class.

7.   The this reference holds the reference of the current object in context.

8.   The static members are also known as class member/data.

9.   In Java, uninitialized constants can be created which are known as blank finals.

10. Garbage collector is a program which runs in the background and claims the unused memory blocks.

11. Java has no destructor.

REVIEW QUESTIONS

1.   What is an object and class? Explain with an example.

2.   What is the difference between class method (static) and instance method?

3.   What is the difference between public member and private member of a class?

4.   Is it legal for a static method to invoke a non-static method? Yes or No. If no, give reason.

5.   Can an abstract method be declared final or static?

6.   When do we declare a method of a class static?

7.   Describe the different level of access protection available in Java.

8.   When do we declare a member variable method or class final?

9.   State true/false:

(a) Abstract class cannot be instantiated.

(b) A final method can be overridden.

(c) Declaring a method synchronized guarantees that the deadlock cannot occur.

(d) Volatile modifier is used to modify by synchronous threads.

10. What is the error in the following code snippet?

 class JPS_test
 {
    abstract void view();
 }

11. Write short notes on the following

(a) this

(b) transient

(c) volatile.

12. Compare and contrast concrete class and abstract class.

13. What is synchronization? Why do we need it?

14. Design a class to represent account, include the following members.

Data Members

Name of depositor-string

Account Number-int

Type of Account-boolean

Balance amount-double

Methods

(a) To assign initial values (using constructor)

(b) To deposit an amount after checking balance and minimum balance 50.

(c) To display the name and balance.

15. Distinguish between the two statements:

JPS c2 = new JPS(c1);
JPS c2 = c1;

c1 and c2 are objects of JPS class.

16. Java does not support destructor. Discuss.

17. Why do we need finalize () method?

18. State True or False: The compiler automatically creates a default constructor for the class, if it has no other constructor declared explicitly.

19. Create a class object interest with a constructor. Write a Java program to find the simple interests using the formula.

Simple Interest = PNR/100

P-principle, N-number of year, R-rate of interest

20. Explain the constructor method. How does it differ from other member function?

21. Develop a program to illustrate a copy constructor so that a string may be duplicated into another variable either by assigning or copying.

22. Write a program to find the volume of a box that has its sides w, h, d as width, height, and depth, respectively. Its volume is v = w * h * d and also find the surface area given by the formula s = 2(wh +hd + dw).

23. Write a program using

(a) Default constructor.

(b) Arguments constructor.

(c) Copy constructor.

To find the area of a rectangle using the following formula area = length * breadth.

24. Write a program simply prints "Wonder of objects" inside the main method. Without using any print statement or concrete methods or dot operators inside the main method.

25. A class weight is having a data member pound, which will have the weight in pounds.Using a conversion function, convert the weight in pounds to weight in kilograms which is of double type. Write a program to do this.

1 pounds = 1 kg/0.453592

Use default constructor to initial assignment of 1000 pounds.

26. Why does the compiler generate the following error: Exception in thread "main" java.lang. NoSuchMethodError: main?

27. Which of the following signatures is valid for the main() method? Justify.

(a) public static void main(String rk[])

(b) static public void main(String argv)

(c) public static void main(String [] [] args)

(d) public static int main(String args[])

28. Can we have more than one default constructor?

29. For a class Animal, write a method sleeps() that uses only one instance variable of Animal. The code

Animal a = new Animal
("fido","woof");
a.sleep();

causes the output

fido is sleeping

30. Define overloaded method and illustrate your definition with a concise and appropriate Java example or your own. Do not use a built-in method as your example; write one of your own.

31. Write code that proves the following statement: If a name can refer to either a local variable or a parameter, that name refers to the local variable.

32. Consider the following class:

   class JPS
   {
      private int var;
      //..................
      public static void JPS1()
      {
       JPS a = new JPS();
       System.out.println(a.var);
        }
      //.................
   }

Does this compile? Does static method JPS1 reference an instance variable? Why is it allowed here?

33. College students typically have at least the following properties: last name, first name, major, home, city, and home state. Following the guidelines of this chapter design a class Student. Write and run drivers that test and demonstrate the capabilities you have built into your class.

34. Consider the following code:

class JPS
{
   private int var;
   //.................
   public static void JPS1()
   {
    System.out.println(var);
   }
   //.................
}

It will not compile. Explain why.

35. How does Java react if we use private instead of public? Explain.

36. How does Java react if we omit the static modifier? Explain.

37. How does Java react if we omit the phrase throws exception? Explain.

Multiple Choice Questions

1.   A class is the basic unit of

(a) function

(b) inheritance

(c) encapsulation

(d) none of the above

2.   The class is an abstract data type (ADT) so creation of class simply creates a

(a) function-like structure

(b) abstraction

(c) template

(d) none of the above

3.   The default value of long data types for class is

(a) false

(b) 0L

(c) (short)0

(d) none of the above

4.   The lifetime of a static variable is the

(a) entire program

(b) only in main method

(c) only inside the class

(d) none of the above

5.   All static variables get their default initial value as _____ when first object of a class is created.

(a) 0

(b) 1

(c) 2

(d) 3

6.   The constructor is always

(a) private

(b) public

(c) protected

(d) none of the above

7.   Find the correct statement.

(a) We cannot pass argument in the constructor

(b) We can create only one constructor for a program

(c) Constructor does not have any return type, not even void

(d) None of the above

8.   We can create _____ constructor in the program

(a) 1

(b) 3

(c) 5

(d) no limit

9.   A copy constructor is a constructor in which ____ object is passed as argument.

(a) single

(b) two

(c) three

(d) none

10. The code given below shows the example for

JPS obj1 = new JPS();
JPS obj2 = new JPS (obj1);

(a) Constructor

(b) Destructor

(c) Copy constructor

(d) None of the above

11. this reference is

(a) implicit reference

(b) explicit reference

(c) both (a) and (b)

(d) none of the above

12. this reference is a built-in reference can only used within

(a) static function of the class

(b) non-static function of the class

(c) cannot be used

(d) none of the above

13. In Java automatic memory management is done by

(a) this reference

(b) destructor

(c) garbage collection

(d) none of the above

14. finalize method is used for

(a) reclaiming the memory

(b) automatic memory management

(c) overriding for clean-up work

(d) none of the above

KEY FOR MULTIPLE CHOICE QUESTIONS

1.   c

2.   c

3.   b

4.   a

5.   a

6.   b

7.   c

8.   d

9.   a

10. c

11. a

12. b

13. c

14. c

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.181.36