SlideShare a Scribd company logo
z
INTRODUCTION
TO JAVA
z
Module II
Classes: Class fundamentals, declaring
Objects, assigning object reference
variables, introducing methods,
constructors, this keyword, garbage
collection, the finalize() method.
A Closer Look at Methods and Classes:
Overloading methods, using objects as
parameters, returning objects, introducing
access control, understanding static,
introducing final.
z
Class Fundamentals
 “class” is a template for an object,
and an “object” is an instance of a
class.
 “class” is also called as blueprint
that object follows
 “objects” are real world entities. It
consists of an properties and tasks.
 “objects” are called as an instance
of a class
z
The General Form of a Class
 Defining a class is by specifying the data that it contains and the code that operates on that data.
 A class is declared by use of the class keyword.
 The general form of a class definition is shown here:
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
}
z
The General
Form of a
Class
(Contd…)
THE DATA, OR
VARIABLES, DEFINED
WITHIN A CLASS ARE
CALLED INSTANCE
VARIABLES.
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, IT IS THE
METHODS THAT
DETERMINE HOW A
CLASS DATA CAN BE
USED.
z
A SIMPLE CLASS
•Here is a class called Box that defines 3 instance
variables: width, height and depth
class Box {
double width;
double height;
double depth;
}
z
Declaring Objects
 Obtaining objects of a class is a two-step process
• Declare a variable of the class type
• Acquire an actual physical copy of the object and assign it to that variable, using
the new operator.
• The new operator dynamically allocates memory for an object and returns a
reference to it.
• This reference is then stored in the variable.
• This reference is more or less, the address in memory of the object allocated
by new.
Box mybox = new Box ( );
Box mybox; // declares reference to object
mybox = new Box( ); // allocate a Box object
• The effect of these two lines of code is depicted below:
z
Classes and Objects (Overview)
• A class defines a new type of data. In this case, the new data type is
called Box.
• This name is used to declare objects of type Box.
• To create a Box object, the following statement is used.
Box mybox = new Box( );
• Each time you create an instance of a class, you are creating an object that
contains its own copy of each instance variable defined by the class.
• Thus every Box object will contain its own copies of the instance
variables: width, height and depth.
• To access these variables, the dot (.) operator is used.
• The dot operator links the name of the object with the name of an
instance variable.
eg. mybox.width = 100;
Program
/* A program that uses the Box class.
Call this file BoxDemo.java*/
class Box {
double width;
double height;
double depth;
};
// This class declares an object of type Box.
class BoxDemo {
public static void main(String args[])
{
Box mybox = new Box();
double vol;
mybox.width = 10; //assign values to mybox's instance variables
mybox.height = 20; mybox.depth = 15;
//compute volume of box
vol = mybox.width * mybox.height * mybox.depth;
System.out.println("Volume is " + vol);
}
Program
• When the above program is compiled, two
.class files have been created, one for Box
and one for BoxDemo.
• The Java compiler automatically puts each
class into its .class file.
• It is not necessary for both the Box and the
BoxDemo class to actually be in the same
source file.
• But to run this program, BoxDemo.class has to
be executed.
• .
Program
 each object has its own copies of the
instance variables.
 This means that if you have
two Box objects, each has its own copy
of depth, width, and height.
 It is important to understand that changes
to the instance variables of one object
have no effect on the instance variables of
another.
 For example, the following program
declares two Box objects:
z
Program
13
public static void main(String args[])
{
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// assign values to mybox1's instance variables mybox1.width = 10;
mybox1.height = 20; mybox1.depth = 15;mybox2.depth = 9
/* assign different values to mybox2's instance variables */
mybox2.width = 3; mybox2.height = 6; mybox2.depth = 9;
// compute volume of first box
vol = mybox1.width * mybox1.height * mybox1.depth;
System.out.println("Volume is " + vol);
// compute volume of second box
vol = mybox2.width * mybox2.height * mybox2.depth;
System.out.println("Volume is " + vol);
}
z
ASSIGNING OBJECT REFERENCE VARIABLES
Consider the following fragment,
Box b1 = new Box( );
Box b2 = b1;
• When this fragment is executed, both b1 and b2 will refer to
the same object.
• The assignment of b1 to b2 did not allocate any memory or
copy any part of the original part.
• 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.
z
• Although b1 and b2 refer to the same object, they are not linked in any other
way.
Box b1 = new Box( ); Box b2 = b1;
//….
b1 = null;
• The above assignment (b1 = null;) will simply unhook b1 from the original
object, without affecting the object or affecting b2.
z
NEW OPERATOR
• The new operator dynamically allocates memory for an
object.
• General form:
class_var = new Classname( );
• The Classname followed by parenthesis specifies the
constructor for the class.
• A constructor defines what occurs when an object of a
class is created.
• If no explicit constructor is specified, then Java will
automatically supply a default constructor.
• It is possible that new will not be able to allocate memory for
an object because of insufficient memory. If this happens, a
run-time exception will occur.
z
• General form of a method
type name(parameter_list)
{
//body of method
}
• Here, type specifies the type of data returned by the method.
• If the method does not return any value, its return type must be void.
• The 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.
• 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;
Introducing Methods
z
• Methods are mostly used to access the instance variables
defined by the class. In fact, methods define the interface to
most classes.
• Methods can also be defined to be used internally by the class
itself.
ADDING A METHOD TO THE BOX CLASS
z
ADDING A METHOD TO THE BOX CLASS
// This program includes a method inside the box class.
class Box
{
double width;
double height;
double depth;
// display volume of a box
void volume()
{
System.out.print("Volume is ");
System.out.println(width * height * depth);
}
}
class Main
{
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to mybox2's instance variables */
mybox2.width = 3; mybox2.height = 6; mybox2.depth = 9;
//display volume of first box
mybox1.volume();
//display volume of second box
mybox2.volume();
}
}
z
RETURNING A VALUE
• vol is a variable that will receive the
value returned by volume( )
• 2 important things about returning values
• The type of the data returned by a method
must be compatible with the return type
specified by the method.
• The variable receiving the value returned
by a method must also be compatible with
the return type specified for the method.
z
RETURNING A VALUE
// Now, volume() returns the volume of a box.
class Box
{
double width;
double height;
double depth;
// compute and return volume
double volume()
{
return width * height * depth;
}
}
class Main
{
public static void main(String args[]) { Box mybox1 = new Box();
Box mybox2 = new Box(); double vol;
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to mybox2's instance variables */
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
//get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
z
• Parameters allow a method to be generalized.
• A parameterized method can operate on a variety of data and/or can be used in a number of slightly
different situations.
Ex:
int square(int i)
{
return i * i;
}
• square( ) will return the square of whatever value it is called with x = square(5); // x equals 25
• But if you write the following function, each time it will return same value and cannot be used in general
purpose form
int square()
{
return 10 * 10;
}
ADDING A METHOD THAT TAKES PARAMETERS
z
• Parameter & Argument
• A parameter is a variable defined by a method
that receives a value when the method is called.
• An argument is a value that is passed to a
method when it is invoked
• Ex: here 10 is an argument and i is a parameter
public class Main
{
int sq(int i)
{return i * i;
}
public static void main(String[] args)
{ int ans=sq(10);
System.out.println(ans);
}
}
z
//compute and return volume
double volume()
{
return width * height * depth;
}
// sets dimensions of box
void setDim(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
}
class Main {
public static void main(String args[])
{
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
//initialize each box
mybox1.setDim(10, 20, 15);
mybox2.setDim(3, 6, 9);
//get volume of first box
z
• Java allows objects to initialize themselves when
they are created.
• This automatic initialization is performed
through the use of a constructor.
• 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 immediately after the object is created
before the new operator completes.
CONSTRUCTORS
z
Constructors (Contd…)
• They have no return type, not even void, because the implicit return type of a
class’ constructor is the class itself.
 It is the constructor’s job to initialize the internal state of an object so that the
code creating an instance will have a fully initialized, usable object
immediately.
• When a constructor is not explicitly
defined, Java creates a default constructor
for a class, that automatically initializes all
instance variables to zero.
PARAMETERIZED CONSTRUCTORS
• If we need to create Box objects of various
dimensions, solution is to add parameters to
the constructor.
z
{
System.out.println("Constructing Box");
width = 10;
height = 10;
depth = 10;
}
// compute and return volume
double volume()
{
return width * height * depth;
}
}
class Main {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
z
Box(double w, double h, double d)
{
System.out.println("Constructing Box");
width = w; height = h; depth = d;
}
// compute and return volume
double volume()
{
return width * height * depth;
}
}
class Main {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box(10,20,15);
Box mybox2 = new Box(3,6,9);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
z
this keyword
 Java defines the this keyword, that can be used inside any method to refer
to the current object.i.e., this is always a reference to the object on which
the method was invoked.
Eg. Box(double w, double h, double d)
{
this.width = w;
this.height = h;
this.depth = d;
}
Inside Box( ), this will always refer to the invoking object.
Instance Variable Hiding
• It is illegal in Java to declare two local variables with the same name
inside the same or enclosing scopes.
• When a local variable has the same name as an instance variable, the local
variable hides the instance variable.
• this keyword lets you refer directly to the object, you can use it to resolve any
name collisions that might occur between instance variables and local
variables.
Eg. Box(double width, double height, double
depth){ this.width = width;
this.height = height;
this.depth = depth;
}
• Using of this keyword overcomes instance variable hiding.
GARBAGE COLLECTION
• In C++, dynamically allocated objects must be manually released by use
of a delete operator.
• Java handles deallocation automatically, when no references to an object
exist, then that object is assumed to be no longer needed, and the memory
occupied by the object can be reclaimed. This technique is called Garbage
collection.
The finalize( ) Method
• If an object is holding some non-Java resources such as a file handle or
window character font, then these resources must be freed before that
object is destroyed.
• Java provides a mechanism called finalization and by using this
finalization, specific actions can be defined that will occur when an object
is just to be reclaimed by the garbage collector.
• To add a finalizer to a class, the finalize( ) method has to be defined.
• Inside the finalize( ) method, specify those actions that must be performed
before an object is destroyed.
• The garbage collector runs periodically, checking for objects that are no
longer referenced by any running state or indirectly through other
referenced objects.
• Right before an asset is freed, the Java runtime system calls the finalize( )
method on the object.
• General form
protected void finalize( )
{
//finalization code
}
• The keyword protected is a specifier that prevent access to finalize( ) by
code defined outside its class.
• finalize( ) is only called just prior to garbage collection.
• We cannot know when or even if finalize( ) will be executed, so our
program should provide other means of releasing system resources.
• It must not rely on finalize( ) for normal program execution.
z
Overloading Methods
z
Overloading Methods
 In Java it is possible to define two or more methods within the same class that
share the same name, as long as their parameter declarations are different.
 When an overloaded method is invoked, Java uses the type and/or number of
arguments as its guide to determine which version of the overloaded method to
actually call.
 Thus, overloaded methods must differ in the type and/or number of their
parameters.
z
Three ways to overload a method
1. Number of parameters.
For example: This is a valid case of overloading
add(int, int)
add(int, int, int)
2. Data type of parameters.
For example:
add(int, int)
add(int, float)
3. Sequence of Data type of parameters.
For example:
add(int, float)
add(float, int)
Method overloading is an example of Static Polymorphism.
Points to Note:
1. Static Polymorphism is also known as compile time binding or early binding.
2. Static binding happens at compile time. Method overloading is an example of static binding where
binding of method call to its definition happens at Compile time.
z
Overloading Constructors
In addition to overloading normal methods, you can also overload constructor
methods.
z
Using Objects as Parameters
•So far, we have only been using simple types as parameters
to methods.
• However, it is both correct and common to pass objects to
methods. For example, consider the following short program:
z
Returning Objects
 A method can return any type of data, including class types that you
create.
 For example, in the following program, the incrByTen( ) method
returns an object in which the value of a is ten greater than it is in
the invoking object.
 Program
 each time incrByTen( ) is invoked, a new object is created, and a
reference to it is returned to the calling routine.
z
 Access control is a mechanism, an attribute of
encapsulation which restricts the access of
certain members of a class to specific parts of
a program. Access to members of a class can
be controlled using the access modifiers. There
are four access modifiers in Java. They are:
1.public
2.protected
3.Private
 By default access modifier will be public, if its
not specified explicitly
Introducing Access Control - Java
z
Lexical Issues
 public :When a member of a class is modified by public,
then that member can be accessed by any other code.
 private :When a member of a class is specified as private,
then that member can only be accessed by other members
of its class.
 protected applies only when inheritance is involved.
 Ex: to declare members with access specifiers
 public int i;
 private double j;
 private int myMethod(int a, char b)
z
 Program
 inside the Test class, a uses default access, which for this example is the same as
specifying public.
 b is explicitly specified as public.
 Member c is given private access. This means that it cannot be accessed by code outside of
its class. So, inside the AccessTest class, c cannot be used directly. It must be accessed
through its public methods: setc( ) and getc( ).
z
 The static keyword is used when a member variable of a class has to be
shared between all the instances of the class.
 We can use static variables when sharing data.
 When objects of its class are declared, no copy of a static variable is made. Instead,
all instances of the class share the same static variable.
 Methods declared as static have several restrictions:
 They can only directly call other static methods.
 They can only directly access static data.
 They cannot refer to this or super in any way.
Enter a number:4 4 is even number enter a number:5
Understanding static - Java
z
 The following example shows a class that has a static method,
some static variables, and a static initialization block:
 Program
 As soon as the UseStatic class is loaded, all of the static statements
are run. First, a is set to 3, then the static block executes, which
prints a message and then initializes b to a*4 or 12. Then main( ) is
called, which calls meth( ), passing 42 to x. The
three println( ) statements refer to the two static variables a and b,
as well as to the local variable x.
 to call a static method from outside its class, you can do so
using the following general form:
 classname.method( )
 Here, classname is the name of the class in which the static
method is declared.
z
Introducing final – Java
 Once a final variable has been assigned, it always contains the same value
 initialize a final field can be done in one of two ways:
 First, you can give it a value when it is declared.
 Second, you can assign it a value within a constructor.
 The first approach is the most common. Here is an example:
 final int FILE_NEW = 1;
 final int FILE_OPEN = 2;
 final int FILE_SAVE = 3;
 final int FILE_SAVEAS = 4;
 final int FILE_QUIT = 5;

More Related Content

PPTX
JAVA Module 2____________________--.pptx
Radhika Venkatesh
 
PPT
5.CLASSES.ppt(MB)2022.ppt .
happycocoman
 
PPTX
Mpl 9 oop
AHHAAH
 
PPTX
unit 2 java.pptx
AshokKumar587867
 
PPTX
Chapter4.pptxdgdhgfshsfhtgjsjryjusryjryjursyj
berihun18
 
PPTX
Class object method constructors in java
Raja Sekhar
 
PPTX
Classes, Inheritance ,Packages & Interfaces.pptx
DivyaKS18
 
PDF
Java-Module 3-PPT-TPS.pdf.Java-Module 3-PPT-TPS.pdf
kakarthik685
 
JAVA Module 2____________________--.pptx
Radhika Venkatesh
 
5.CLASSES.ppt(MB)2022.ppt .
happycocoman
 
Mpl 9 oop
AHHAAH
 
unit 2 java.pptx
AshokKumar587867
 
Chapter4.pptxdgdhgfshsfhtgjsjryjusryjryjursyj
berihun18
 
Class object method constructors in java
Raja Sekhar
 
Classes, Inheritance ,Packages & Interfaces.pptx
DivyaKS18
 
Java-Module 3-PPT-TPS.pdf.Java-Module 3-PPT-TPS.pdf
kakarthik685
 

Similar to JAVA Module 2 ppt on classes and objects and along with examples (20)

PPTX
Chapter ii(oop)
Chhom Karath
 
PPTX
Classes, Objects and Method - Object Oriented Programming with Java
Radhika Talaviya
 
PPT
packages and interfaces
madhavi patil
 
PPTX
class object.pptx
Killmekhilati
 
PPTX
Chapter 3
siragezeynu
 
PDF
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Tushar B Kute
 
DOCX
java classes
Vasu Devan
 
PDF
Java Basics - Part2
Vani Kandhasamy
 
PPTX
Java
nirbhayverma8
 
PPTX
Chap2 class,objects
raksharao
 
PPTX
Core java complete ppt(note)
arvind pandey
 
PDF
Session 3 Constructors, Types, Overloading, Static MethodsNotes.pdf
tabbu23
 
PPT
Core Java unit no. 1 object and class ppt
Mochi263119
 
PPTX
Lecture 5
talha ijaz
 
PPTX
Ch-2ppt.pptx
ssuser8347a1
 
PPT
New operator and methods.15
myrajendra
 
PPTX
Getters_And_Setters.pptx
Kavindu Sachinthe
 
PPTX
Chap-2 Classes & Methods.pptx
chetanpatilcp783
 
PPT
Lecture 2 classes i
the_wumberlog
 
PPTX
Classes, objects in JAVA
Abhilash Nair
 
Chapter ii(oop)
Chhom Karath
 
Classes, Objects and Method - Object Oriented Programming with Java
Radhika Talaviya
 
packages and interfaces
madhavi patil
 
class object.pptx
Killmekhilati
 
Chapter 3
siragezeynu
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Tushar B Kute
 
java classes
Vasu Devan
 
Java Basics - Part2
Vani Kandhasamy
 
Chap2 class,objects
raksharao
 
Core java complete ppt(note)
arvind pandey
 
Session 3 Constructors, Types, Overloading, Static MethodsNotes.pdf
tabbu23
 
Core Java unit no. 1 object and class ppt
Mochi263119
 
Lecture 5
talha ijaz
 
Ch-2ppt.pptx
ssuser8347a1
 
New operator and methods.15
myrajendra
 
Getters_And_Setters.pptx
Kavindu Sachinthe
 
Chap-2 Classes & Methods.pptx
chetanpatilcp783
 
Lecture 2 classes i
the_wumberlog
 
Classes, objects in JAVA
Abhilash Nair
 
Ad

Recently uploaded (20)

PDF
EVS+PRESENTATIONS EVS+PRESENTATIONS like
saiyedaqib429
 
PDF
Top 10 read articles In Managing Information Technology.pdf
IJMIT JOURNAL
 
PDF
Biodegradable Plastics: Innovations and Market Potential (www.kiu.ac.ug)
publication11
 
PPT
Ppt for engineering students application on field effect
lakshmi.ec
 
PPTX
Information Retrieval and Extraction - Module 7
premSankar19
 
PPTX
Inventory management chapter in automation and robotics.
atisht0104
 
PPTX
MSME 4.0 Template idea hackathon pdf to understand
alaudeenaarish
 
PDF
The Effect of Artifact Removal from EEG Signals on the Detection of Epileptic...
Partho Prosad
 
PDF
LEAP-1B presedntation xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
hatem173148
 
PDF
Chad Ayach - A Versatile Aerospace Professional
Chad Ayach
 
PDF
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
PDF
Zero carbon Building Design Guidelines V4
BassemOsman1
 
PPTX
IoT_Smart_Agriculture_Presentations.pptx
poojakumari696707
 
PPTX
easa module 3 funtamental electronics.pptx
tryanothert7
 
PDF
Traditional Exams vs Continuous Assessment in Boarding Schools.pdf
The Asian School
 
PDF
FLEX-LNG-Company-Presentation-Nov-2017.pdf
jbloggzs
 
PDF
July 2025: Top 10 Read Articles Advanced Information Technology
ijait
 
PPTX
22PCOAM21 Data Quality Session 3 Data Quality.pptx
Guru Nanak Technical Institutions
 
PDF
settlement FOR FOUNDATION ENGINEERS.pdf
Endalkazene
 
PPT
SCOPE_~1- technology of green house and poyhouse
bala464780
 
EVS+PRESENTATIONS EVS+PRESENTATIONS like
saiyedaqib429
 
Top 10 read articles In Managing Information Technology.pdf
IJMIT JOURNAL
 
Biodegradable Plastics: Innovations and Market Potential (www.kiu.ac.ug)
publication11
 
Ppt for engineering students application on field effect
lakshmi.ec
 
Information Retrieval and Extraction - Module 7
premSankar19
 
Inventory management chapter in automation and robotics.
atisht0104
 
MSME 4.0 Template idea hackathon pdf to understand
alaudeenaarish
 
The Effect of Artifact Removal from EEG Signals on the Detection of Epileptic...
Partho Prosad
 
LEAP-1B presedntation xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
hatem173148
 
Chad Ayach - A Versatile Aerospace Professional
Chad Ayach
 
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
Zero carbon Building Design Guidelines V4
BassemOsman1
 
IoT_Smart_Agriculture_Presentations.pptx
poojakumari696707
 
easa module 3 funtamental electronics.pptx
tryanothert7
 
Traditional Exams vs Continuous Assessment in Boarding Schools.pdf
The Asian School
 
FLEX-LNG-Company-Presentation-Nov-2017.pdf
jbloggzs
 
July 2025: Top 10 Read Articles Advanced Information Technology
ijait
 
22PCOAM21 Data Quality Session 3 Data Quality.pptx
Guru Nanak Technical Institutions
 
settlement FOR FOUNDATION ENGINEERS.pdf
Endalkazene
 
SCOPE_~1- technology of green house and poyhouse
bala464780
 
Ad

JAVA Module 2 ppt on classes and objects and along with examples

  • 2. z Module II Classes: Class fundamentals, declaring Objects, assigning object reference variables, introducing methods, constructors, this keyword, garbage collection, the finalize() method. A Closer Look at Methods and Classes: Overloading methods, using objects as parameters, returning objects, introducing access control, understanding static, introducing final.
  • 3. z Class Fundamentals  “class” is a template for an object, and an “object” is an instance of a class.  “class” is also called as blueprint that object follows  “objects” are real world entities. It consists of an properties and tasks.  “objects” are called as an instance of a class
  • 4. z The General Form of a Class  Defining a class is by specifying the data that it contains and the code that operates on that data.  A class is declared by use of the class keyword.  The general form of a class definition is shown here: 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 }
  • 5. z The General Form of a Class (Contd…) THE DATA, OR VARIABLES, DEFINED WITHIN A CLASS ARE CALLED INSTANCE VARIABLES. 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, IT IS THE METHODS THAT DETERMINE HOW A CLASS DATA CAN BE USED.
  • 6. z A SIMPLE CLASS •Here is a class called Box that defines 3 instance variables: width, height and depth class Box { double width; double height; double depth; }
  • 7. z Declaring Objects  Obtaining objects of a class is a two-step process • Declare a variable of the class type • Acquire an actual physical copy of the object and assign it to that variable, using the new operator. • The new operator dynamically allocates memory for an object and returns a reference to it. • This reference is then stored in the variable. • This reference is more or less, the address in memory of the object allocated by new. Box mybox = new Box ( ); Box mybox; // declares reference to object mybox = new Box( ); // allocate a Box object
  • 8. • The effect of these two lines of code is depicted below:
  • 9. z Classes and Objects (Overview) • A class defines a new type of data. In this case, the new data type is called Box. • This name is used to declare objects of type Box. • To create a Box object, the following statement is used. Box mybox = new Box( ); • Each time you create an instance of a class, you are creating an object that contains its own copy of each instance variable defined by the class. • Thus every Box object will contain its own copies of the instance variables: width, height and depth. • To access these variables, the dot (.) operator is used. • The dot operator links the name of the object with the name of an instance variable. eg. mybox.width = 100;
  • 10. Program /* A program that uses the Box class. Call this file BoxDemo.java*/ class Box { double width; double height; double depth; }; // This class declares an object of type Box. class BoxDemo { public static void main(String args[]) { Box mybox = new Box(); double vol; mybox.width = 10; //assign values to mybox's instance variables mybox.height = 20; mybox.depth = 15; //compute volume of box vol = mybox.width * mybox.height * mybox.depth; System.out.println("Volume is " + vol); }
  • 11. Program • When the above program is compiled, two .class files have been created, one for Box and one for BoxDemo. • The Java compiler automatically puts each class into its .class file. • It is not necessary for both the Box and the BoxDemo class to actually be in the same source file. • But to run this program, BoxDemo.class has to be executed. • .
  • 12. Program  each object has its own copies of the instance variables.  This means that if you have two Box objects, each has its own copy of depth, width, and height.  It is important to understand that changes to the instance variables of one object have no effect on the instance variables of another.  For example, the following program declares two Box objects:
  • 13. z Program 13 public static void main(String args[]) { Box mybox1 = new Box(); Box mybox2 = new Box(); double vol; // assign values to mybox1's instance variables mybox1.width = 10; mybox1.height = 20; mybox1.depth = 15;mybox2.depth = 9 /* assign different values to mybox2's instance variables */ mybox2.width = 3; mybox2.height = 6; mybox2.depth = 9; // compute volume of first box vol = mybox1.width * mybox1.height * mybox1.depth; System.out.println("Volume is " + vol); // compute volume of second box vol = mybox2.width * mybox2.height * mybox2.depth; System.out.println("Volume is " + vol); }
  • 14. z ASSIGNING OBJECT REFERENCE VARIABLES Consider the following fragment, Box b1 = new Box( ); Box b2 = b1; • When this fragment is executed, both b1 and b2 will refer to the same object. • The assignment of b1 to b2 did not allocate any memory or copy any part of the original part. • 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.
  • 15. z • Although b1 and b2 refer to the same object, they are not linked in any other way. Box b1 = new Box( ); Box b2 = b1; //…. b1 = null; • The above assignment (b1 = null;) will simply unhook b1 from the original object, without affecting the object or affecting b2.
  • 16. z NEW OPERATOR • The new operator dynamically allocates memory for an object. • General form: class_var = new Classname( ); • The Classname followed by parenthesis specifies the constructor for the class. • A constructor defines what occurs when an object of a class is created. • If no explicit constructor is specified, then Java will automatically supply a default constructor. • It is possible that new will not be able to allocate memory for an object because of insufficient memory. If this happens, a run-time exception will occur.
  • 17. z • General form of a method type name(parameter_list) { //body of method } • Here, type specifies the type of data returned by the method. • If the method does not return any value, its return type must be void. • The 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. • 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; Introducing Methods
  • 18. z • Methods are mostly used to access the instance variables defined by the class. In fact, methods define the interface to most classes. • Methods can also be defined to be used internally by the class itself. ADDING A METHOD TO THE BOX CLASS
  • 19. z ADDING A METHOD TO THE BOX CLASS // This program includes a method inside the box class. class Box { double width; double height; double depth; // display volume of a box void volume() { System.out.print("Volume is "); System.out.println(width * height * depth); } } class Main { public static void main(String args[]) { Box mybox1 = new Box(); Box mybox2 = new Box(); // assign values to mybox1's instance variables mybox1.width = 10; mybox1.height = 20; mybox1.depth = 15; /* assign different values to mybox2's instance variables */ mybox2.width = 3; mybox2.height = 6; mybox2.depth = 9; //display volume of first box mybox1.volume(); //display volume of second box mybox2.volume(); } }
  • 20. z RETURNING A VALUE • vol is a variable that will receive the value returned by volume( ) • 2 important things about returning values • The type of the data returned by a method must be compatible with the return type specified by the method. • The variable receiving the value returned by a method must also be compatible with the return type specified for the method.
  • 21. z RETURNING A VALUE // Now, volume() returns the volume of a box. class Box { double width; double height; double depth; // compute and return volume double volume() { return width * height * depth; } } class Main { public static void main(String args[]) { Box mybox1 = new Box(); Box mybox2 = new Box(); double vol; // assign values to mybox1's instance variables mybox1.width = 10; mybox1.height = 20; mybox1.depth = 15; /* assign different values to mybox2's instance variables */ mybox2.width = 3; mybox2.height = 6; mybox2.depth = 9; //get volume of first box vol = mybox1.volume(); System.out.println("Volume is " + vol); // get volume of second box vol = mybox2.volume(); System.out.println("Volume is " + vol); } }
  • 22. z • Parameters allow a method to be generalized. • A parameterized method can operate on a variety of data and/or can be used in a number of slightly different situations. Ex: int square(int i) { return i * i; } • square( ) will return the square of whatever value it is called with x = square(5); // x equals 25 • But if you write the following function, each time it will return same value and cannot be used in general purpose form int square() { return 10 * 10; } ADDING A METHOD THAT TAKES PARAMETERS
  • 23. z • Parameter & Argument • A parameter is a variable defined by a method that receives a value when the method is called. • An argument is a value that is passed to a method when it is invoked • Ex: here 10 is an argument and i is a parameter public class Main { int sq(int i) {return i * i; } public static void main(String[] args) { int ans=sq(10); System.out.println(ans); } }
  • 24. z //compute and return volume double volume() { return width * height * depth; } // sets dimensions of box void setDim(double w, double h, double d) { width = w; height = h; depth = d; } } class Main { public static void main(String args[]) { Box mybox1 = new Box(); Box mybox2 = new Box(); double vol; //initialize each box mybox1.setDim(10, 20, 15); mybox2.setDim(3, 6, 9); //get volume of first box
  • 25. z • Java allows objects to initialize themselves when they are created. • This automatic initialization is performed through the use of a constructor. • 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 immediately after the object is created before the new operator completes. CONSTRUCTORS
  • 26. z Constructors (Contd…) • They have no return type, not even void, because the implicit return type of a class’ constructor is the class itself.  It is the constructor’s job to initialize the internal state of an object so that the code creating an instance will have a fully initialized, usable object immediately. • When a constructor is not explicitly defined, Java creates a default constructor for a class, that automatically initializes all instance variables to zero. PARAMETERIZED CONSTRUCTORS • If we need to create Box objects of various dimensions, solution is to add parameters to the constructor.
  • 27. z { System.out.println("Constructing Box"); width = 10; height = 10; depth = 10; } // compute and return volume double volume() { return width * height * depth; } } class Main { public static void main(String args[]) { // declare, allocate, and initialize Box objects Box mybox1 = new Box(); Box mybox2 = new Box(); double vol; // get volume of first box vol = mybox1.volume(); System.out.println("Volume is " + vol);
  • 28. z Box(double w, double h, double d) { System.out.println("Constructing Box"); width = w; height = h; depth = d; } // compute and return volume double volume() { return width * height * depth; } } class Main { public static void main(String args[]) { // declare, allocate, and initialize Box objects Box mybox1 = new Box(10,20,15); Box mybox2 = new Box(3,6,9); double vol; // get volume of first box vol = mybox1.volume(); System.out.println("Volume is " + vol);
  • 29. z this keyword  Java defines the this keyword, that can be used inside any method to refer to the current object.i.e., this is always a reference to the object on which the method was invoked. Eg. Box(double w, double h, double d) { this.width = w; this.height = h; this.depth = d; } Inside Box( ), this will always refer to the invoking object.
  • 30. Instance Variable Hiding • It is illegal in Java to declare two local variables with the same name inside the same or enclosing scopes. • When a local variable has the same name as an instance variable, the local variable hides the instance variable. • this keyword lets you refer directly to the object, you can use it to resolve any name collisions that might occur between instance variables and local variables. Eg. Box(double width, double height, double depth){ this.width = width; this.height = height; this.depth = depth; } • Using of this keyword overcomes instance variable hiding.
  • 31. GARBAGE COLLECTION • In C++, dynamically allocated objects must be manually released by use of a delete operator. • Java handles deallocation automatically, when no references to an object exist, then that object is assumed to be no longer needed, and the memory occupied by the object can be reclaimed. This technique is called Garbage collection. The finalize( ) Method • If an object is holding some non-Java resources such as a file handle or window character font, then these resources must be freed before that object is destroyed. • Java provides a mechanism called finalization and by using this finalization, specific actions can be defined that will occur when an object is just to be reclaimed by the garbage collector.
  • 32. • To add a finalizer to a class, the finalize( ) method has to be defined. • Inside the finalize( ) method, specify those actions that must be performed before an object is destroyed. • The garbage collector runs periodically, checking for objects that are no longer referenced by any running state or indirectly through other referenced objects. • Right before an asset is freed, the Java runtime system calls the finalize( ) method on the object. • General form protected void finalize( ) { //finalization code }
  • 33. • The keyword protected is a specifier that prevent access to finalize( ) by code defined outside its class. • finalize( ) is only called just prior to garbage collection. • We cannot know when or even if finalize( ) will be executed, so our program should provide other means of releasing system resources. • It must not rely on finalize( ) for normal program execution.
  • 35. z Overloading Methods  In Java it is possible to define two or more methods within the same class that share the same name, as long as their parameter declarations are different.  When an overloaded method is invoked, Java uses the type and/or number of arguments as its guide to determine which version of the overloaded method to actually call.  Thus, overloaded methods must differ in the type and/or number of their parameters.
  • 36. z Three ways to overload a method 1. Number of parameters. For example: This is a valid case of overloading add(int, int) add(int, int, int) 2. Data type of parameters. For example: add(int, int) add(int, float) 3. Sequence of Data type of parameters. For example: add(int, float) add(float, int) Method overloading is an example of Static Polymorphism. Points to Note: 1. Static Polymorphism is also known as compile time binding or early binding. 2. Static binding happens at compile time. Method overloading is an example of static binding where binding of method call to its definition happens at Compile time.
  • 37. z Overloading Constructors In addition to overloading normal methods, you can also overload constructor methods.
  • 38. z Using Objects as Parameters •So far, we have only been using simple types as parameters to methods. • However, it is both correct and common to pass objects to methods. For example, consider the following short program:
  • 39. z Returning Objects  A method can return any type of data, including class types that you create.  For example, in the following program, the incrByTen( ) method returns an object in which the value of a is ten greater than it is in the invoking object.  Program  each time incrByTen( ) is invoked, a new object is created, and a reference to it is returned to the calling routine.
  • 40. z  Access control is a mechanism, an attribute of encapsulation which restricts the access of certain members of a class to specific parts of a program. Access to members of a class can be controlled using the access modifiers. There are four access modifiers in Java. They are: 1.public 2.protected 3.Private  By default access modifier will be public, if its not specified explicitly Introducing Access Control - Java
  • 41. z Lexical Issues  public :When a member of a class is modified by public, then that member can be accessed by any other code.  private :When a member of a class is specified as private, then that member can only be accessed by other members of its class.  protected applies only when inheritance is involved.  Ex: to declare members with access specifiers  public int i;  private double j;  private int myMethod(int a, char b)
  • 42. z  Program  inside the Test class, a uses default access, which for this example is the same as specifying public.  b is explicitly specified as public.  Member c is given private access. This means that it cannot be accessed by code outside of its class. So, inside the AccessTest class, c cannot be used directly. It must be accessed through its public methods: setc( ) and getc( ).
  • 43. z  The static keyword is used when a member variable of a class has to be shared between all the instances of the class.  We can use static variables when sharing data.  When objects of its class are declared, no copy of a static variable is made. Instead, all instances of the class share the same static variable.  Methods declared as static have several restrictions:  They can only directly call other static methods.  They can only directly access static data.  They cannot refer to this or super in any way. Enter a number:4 4 is even number enter a number:5 Understanding static - Java
  • 44. z  The following example shows a class that has a static method, some static variables, and a static initialization block:  Program  As soon as the UseStatic class is loaded, all of the static statements are run. First, a is set to 3, then the static block executes, which prints a message and then initializes b to a*4 or 12. Then main( ) is called, which calls meth( ), passing 42 to x. The three println( ) statements refer to the two static variables a and b, as well as to the local variable x.  to call a static method from outside its class, you can do so using the following general form:  classname.method( )  Here, classname is the name of the class in which the static method is declared.
  • 45. z Introducing final – Java  Once a final variable has been assigned, it always contains the same value  initialize a final field can be done in one of two ways:  First, you can give it a value when it is declared.  Second, you can assign it a value within a constructor.  The first approach is the most common. Here is an example:  final int FILE_NEW = 1;  final int FILE_OPEN = 2;  final int FILE_SAVE = 3;  final int FILE_SAVEAS = 4;  final int FILE_QUIT = 5;