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.
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).
A new class with fields (data members) and methods (member functions) is given below:
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 |
For char
, the default value is not printed, rather a blank space will be visible. See the following program.
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
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.
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;
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.
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.
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.
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.
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.
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.
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
.
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:
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.
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).
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.
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.
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.
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.
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.
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).
One for class, common to all objects
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.
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.
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.
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);
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.
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.
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.
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
.
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).
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.
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; }
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.
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.
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.
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
.
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.
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.
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.
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
18.191.181.36