Introducing Classes
Anuja.R.Nair
Assistant Professor, CSE
1
Agenda
Concept of class
Creating objects
Declaring objects
Methods
Returning a value
Parameterized methods
Constructors
Garbage Collection
2
Concept of Class
A class is a description of a group of objects with
common properties (attributes) & behavior (operations)
An object is an instance of a class
e.g. Mary is an object of Student class
Jane is an object of Student class
Mary 1001 Jane 1002
name rollNo name 3 rollNo
CONFIDENTIAL© Copyright 2008 Tech
Mahindra Limited
General form of a Class
class classname
{
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list) {
// body of method
}
type methodname2(parameter-list) {
// body of method
}
// ...
type methodnameN(parameter-list) {
// body of method
}
}
4
General form of a Class
Data and variable defined within class are called instance
variable
The code is contained within methods
Collectively, the methods and variables defined within a
class are called members of the class
In most classes, the instance variables are acted upon and
accessed by the methods defined for that class.
Thus, as a general rule, it is the methods that determine
how a class’ data can be used
Class is a template for an object and an object is an
instance of a class.
Java classes do not need to have a main() method.
5
Creating an object
A class declaration only creates a template, it does not
create an actual object.
There are three steps when creating an object from a
class:
Declaration: A variable declaration with a variable name as
an object type.
Instantiation: The 'new' key word is used to create the
object.
Initialization: The 'new' keyword is followed by a call to a
constructor. This call initializes the new object.
6
Creating Objects
The new operator creates a object & returns a reference to it
Memory allocation of objects happens in the heap area
Reference returned can be stored in reference variables
Student obj1; Declare reference to
object
obj1 = new Student();
obj1 is a reference
Or variable
Student obj2 = new Student(“John”);
Allocate a “Student”
object
obj1: Student obj2: Student new keyword
creates an object
name name John
and returns a
reference to it
7 CONFIDENTIAL© Copyright 2008 Tech
Mahindra Limited
Declaring Objects
The new operator dynamically allocates (that is, allocates at
run time) memory for an object and returns a reference to it.
After first line, the “obj1” contains value null, which indicates
that it does not yet point to an actual object. Any attempt to
use “obj1” here results in compile time error.
The next line allocates an actual object and assigns a reference
to it to “obj1”
Now “obj1” can be used as object of “Student”
Initializing other variables like int, short, char etc does not
need new keyword as they are not classes
If new can not allocate memory, it generates exception
8
Constituents of a Class Data Members
(State)
public class Student {
private int rollNo;
private String name;
Constructor
Student(){
//initialize data members
}
Student(String nameParam){
name = nameParam;
}
public int getrollNo (){
Method
return rollNo;
(Behavior)
}
}
The main method may or may not be present depending on whether the class is a starter class
Naming Convention → Class Name: First letter Capital
9 CONFIDENTIAL© Copyright 2008 Tech
Mahindra Limited
A simple Class
10
Objects of Box class
11
Assigning object reference variable
The assignment of b1 to b2 did not allocate any memory or copy any part
of the original object. It simply makes b2 refer to the same object as does
b1.
Basically they are same object with different names
However they are not linked in any way. A subsequent assignment to b1 will
simply unhook b1 from the original object without affecting the object or
affecting b2. For example
When you assign one object reference variable to another object reference
variable, you are not creating a copy of the object, you are only making a copy of
the reference.
12
Lifetime of Objects obj1
Student obj1 = new student();
1
Student obj2 = new student();
Both Student objects now live on the heap Heap
2
→ References : 2
obj2
→ Objects :2
obj1
Student obj3 = obj2;
1
→ References : 3
obj3
→ Objects :2 2
Heap
obj2
13 CONFIDENTIAL© Copyright 2008 Tech
Mahindra Limited
Lifetime of
Objects obj1
obj3 = obj1;
1
obj3
→ References : 3
2
→ Objects :2 Heap
obj2
obj1
obj2 = null;
1
→ Active References : 2
→ Null References :1 obj3
2
Heap
→ Reachable Objects : 1
→ Abandoned objects : 1
obj2
Null Reference This object can be
garbage collected
14 CONFIDENTIAL© Copyright 2008 Tech
Mahindra Limited
Methods
type name (parameter-list) {
//body of method }
type specifies the type of data returned by the method. This can be any valid
type, including class types that you create.
If the method does not return a value, its return type must be void. The
name of the method is specified by name.
Parameters are essentially variables that receive the value of the arguments passed
to the method when it is called. If the method has no parameters, then the
parameter list will be empty.
Methods that have a return type other than void return a value to the calling
routine using the following form of the return statement:
return value;
Here, value is the value returned.
15
Accessing Instance Variables and Methods
/* First create an object */
ObjectReference = new Constructor();
/* Now call a variable as follows */
ObjectReference.variableName;
/* Now you can call a class method as follows */
ObjectReference.MethodName();
16
Adding a method to a Class
17
Returning a value
18
Parameterized Methods
19
Constructors
Special methods used to initialize a newly created object
Called just after memory is allocated for an object
Initialize objects to required or default values at the time of object creation
Not mandatory to write a constructor for each class
A constructor
Has the same name as that of the class
Doesn’t return any value, not even void
May or may not have parameters (arguments)
If a class does not have any constructor, the default constructor is
automatically added
In the absence of a user defined constructor, the compiler initializes
member variables to its default values
Numeric data types are set to 0
Char data types are set to null character (‘\0’)
Reference variables are set to null
20
Constructors
21
Parameterized Constructors
22
Garbage Collection
Garbage collection is the process of reclaiming the unused memory space
and making it available for the future instances.
Objects are dynamically allocated by using the new operator.
In C++, dynamically allocated objects must be manually released by use of a
delete operator.
In C, it is the programmer’s responsibility to de-allocate the dynamically
allocated memory using the free() function.
Java takes a different approach; it handles deallocation for you automatically.
When no references to an object exist, that object is assumed to be no
longer needed, and the memory occupied by the object can be reclaimed.
The garbage collector runs periodically, checking for objects that are no
longer referenced by any running state or indirectly through other
referenced objects.
There is no explicit need to destroy objects as in C++.
Normally a programmer should not think about destroying objects in java.
23
How can an object be unreferenced?
By nulling the reference
Employee e = new Employee();
e = null;
By assigning a reference to another
Employee e1 = new Employee();
Employee e2 = new Employee();
e1 = e2;
//now the first object referred by e1 is available for garbage coll
ection
By anonymous object etc.
new Employee();
24
finalize() method
Sometimes an object will need to perform some action when it is destroyed
For example, if an object is holding some non-Java resource such as a file handle or
character font, then you might want to make sure these resources are freed before
an object is destroyed
You can define specific actions that will occur when an object is just about to be
reclaimed by the garbage collector
Right before an asset is freed, the Java run time calls the finalize() method on the
object
protected is a specifier that prevents access to finalize() by code defined outside
its class
It is important to understand that finalize() is only called just prior to garbage
collection. It is not called when an object goes out-of-scope
Garbage collection is performed by a daemon thread called Garbage
Collector(GC). This thread calls the finalize() method before object is garbage
collected.
25
THANK YOU!!
ANY QUESTIONS??
26