Java class
fundamentals
Mr. M.R.
Solanki
Sr. Lecturer, Information Technology,
[email protected]
SBMP
Learning Outcomes
Students will be able to:
• Write a class in Java
• Instantiate object in Java
• Add member methods in a class
• Introduce constructors in Java
• Describe Garbage Collection process
Defining a class in Java
class syntax
A class is declared by use of the class keyword.
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
}
} //end of class
“
# Java classes do not need to have a main( )
method
# You only specify one if that class is the
starting point for your program
# applets, don’t require a main( ) method at
all
class syntax
A class example
class Box
{
double width;
double height;
double depth;
}
Instantiating an object
in Java
Creating Objects
Obtaining objects of a class is a two-step process:
1. Declare a variable of the class type i.e.
reference
This variable does not define an object.
It is simply a variable that can refer to an
object
We can not apply mathematical operators
i.e. + and – on reference (as allowed in case of
pointer in C/C++)
We can assign one reference to other
reference variable
Syntax: classname ref;
Example: Box mybox;
Creating Objects
2. Acquire an actual, physical copy of the object
and assign it to that variable:
It is performed using new operator.
The new operator dynamically allocates (at run
time) memory
for an object and returns its reference.
This reference is the address of the object
allocated by new in the memory (RAM).
This reference is then stored in the variable
Syntax: ref = new classname();
Example: mybox = new Box();
Creating Objects
RAM
Creating Objects
declaration
Variables
We can assign one reference to other reference as
below:
Box b1 = new Box();
Box b2 = b1;
b1 and b2 will both refer to the same object.
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
Thus, any changes made to the object through b2
will affect the object to which b1 is referring,
since they are the same object
“
# Although b1 and b2 both refer to the same
object, they are not linked in any other way.
For example, If we assign b1 with other object
reference or with null value, it will unhook itself
from original object without affecting the original
object or b2.
Box b1 = new Box();
Box b2 = b1;
// ...
b1 = null;
Here, b1 has been set to null, but b2 still
points to the original object.
Adding method in a
class
Adding Methods
type name(parameter-list) {
// body of method
}
(i) type : type of data returned by the
method.
This can be any valid type
If the method does not return a value, its
return type must be void.
(ii) name : name of the method is specified
by name.
This can be any legal identifier other than
those already used by other items within the
current scope.
Adding Methods
type name(parameter-list) {
// body of method
}
(iii) parameter-list: is a sequence of type
and identifier pairs separated by commas
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.
Adding Methods
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 to be returned.
Adding a Method in Box class
Adding a Method in Box class
statement
statement
about returning values:
“
There are two important things to understand
The type of data returned by a method must be
compatible with the return type specified by the
method. For example, if the return type of some
method is boolean, you could not return an
integer.
The variable receiving the value returned by a
method (i.e. vol, in this case) must also be
compatible with the return type specified for the
method.
While initializing data members in main(), creates 2
“
problems:
1. It is clumsy and error prone.
Example, It would be easy to forget to set a
dimension.
2. In well-designed Java programs, instance
variables should be accessed only through
methods defined by their class. (Encapsulation)
Initializing instance members using setter
method
We can use setter method in Java to initialize the instance
data members of a class:
Initializing instance members using setter
method
Exercise
“
Write the previous program by taking user input
from key board using Scanner class.
Introducing Constructor
in Java
Introducing Constructors
Setter methods are to be called explicitly to
initialize instance data members of an object.
Java allows objects to initialize themselves when
they are created.
This automatic initialization is performed
through the use of a
constructor.
Constructor Properties
A constructor initializes an object immediately
upon creation.
It has the same name as the class in which it
resides and is syntactically similar to a method.
Once defined, the constructor is automatically
called when the object is created, before the
new operator completes.
Constructors don’t have return type, not even
void (the implicit return type of a class’
constructor is the class type itself).
It is the constructor’s job to initialize the
internal state of an object so that the code
Introducing Constructors
Introducing Constructors
provides an
+)
“
Note: (i) If we don’t provide a constructor, Java
automatic constructor (same as C+
(ii) The default values assigned to data
members of a class as per data type are as below:
integer group -> 0
floating point group -> 0.0
boolean -> false
char-> \u0000 or null (‘\0’)
reference variable -> null
Introducing Constructors
Introducing Constructors
Parameterized Constructors
Initialization of data members in parameter less
constructor is not effective way.
In this case, every object’s data is initialized
with the same values.
The easy solution is to add parameters to the
constructor (same as C++)
It is similar to passing parameters to a method.
Parameterized Constructors
The this keyword
Sometimes a method will need to refer to the
object that invoked it.
To allow this, Java defines this keyword.
this can be used inside any method to refer to the
current object
this stores a reference to the object who has
invoked the method presently.
// A redundant use of this
Box(double w, double h, double d)
{
this.width = w;
this.height = h;
this.depth = d;
}
Instance variable Hiding
We can have local variables, i.e. formal
parameters to methods, which overlap with the
names of the class’ instance variables.
When a local variable has the same name as an
instance variable, the local variable hides the
instance variable (local wins)
This is why width, height, and depth were not
used as the names of the parameters to the Box(
) constructor inside the Box class.
Solution:
// Use this to resolve name-space
collisions.
Box(double width, double height, double
depth) {
this.width = width;
this.height = height;
this.depth = depth;
Working of this
Working of this
Garbage Collection
Garbage Collection
In some languages, such as C++, dynamically
allocated objects must be manually released by
use of a delete operator.
Java takes a different approach; it handles
deallocation for you automatically.
The technique that accomplishes this is called
garbage collection.
Garbage Collection
Working:
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.
There is no explicit need to destroy objects as in
C++. Garbage collection only occurs sporadically
(if at all) during the execution of your program
It will not occur simply because one or more
objects exist that are no longer used
Thanks!
Any questions?
You can find me at:
[email protected]Credits
Java The Complete Reference, Ninth E
dition, Herbert Schildt