Chapter02-Classs & Object
Chapter02-Classs & Object
Chapter 02
1
Objectives
After studying this chapter, students should be able to learn:
Classes and Objects
Methods
Constructors
Default Constructors
Parameterized Constructors
Use of this keyword
Use of access specifiers: public, private and protected
Method Overloading
Constructor Overloading
Garbage Collection
2
Introduction
Java is a pure object-oriented language and therefore the
underlying structure of all Java programs is classes.
A class is a template or prototype that defines a type of object.
Everything we wish to represent in a Java program must be
encapsulated in class.
Class defines the state and behaviour of the basic programming
components known as objects.
A class defines the skeleton of an object.
Classes create objects and objects use methods to communicate
between them. This is all about object-oriented programming.
3
Contd.
A class is a blueprint that defines the states and the behaviors
common to all objects of a certain kind.
An object is a software bundle that has State and Behaviour.
1. An Object's state is stored in variables called fields.
2. An Object's behaviour is defined by its methods.
Example 1: Dogs
States: name, color, breed, and “is hungry?”
Behaviors: bark, run, and wag tail
Example 2: Cars
States: color, model, speed, direction
Behaviors: accelerate, turn, change gears
4
Defining a Class
A class is a user-defined data type with a template that serves to
define its properties.
Once a class type has been defined, we can create “variables” of
that type using declaration that are similar to the basic type
declarations.
In Java such variables are known as instance variables, which are
the actual objects.
The basic form of a class definition is:
class classname [extends superclassname]
{
[ variable declaration; ]
[ methods declaration; ]
}
5
Contd.
Everything inside the square brackets [ ] is optional. This means
the following would be a valid class definition:
class Empty
{
}
6
Adding Variables (Fields)
Data is encapsulated in a class by placing data fields inside the
body of the class definition.
These variables are called instance variables (member variables)
because they are created when an object of the class is instantiated.
These variables are created exactly the same way as we declare
local variables.
Example:
class Rectangle
{
int length;
int width;
}
7
Adding Methods
A class with only data fields (and without methods that operate on
that data) has no life.
Methods are declared inside the body of the class but immediately
after the declaration of the instance variables.
The general form of a method declaration is:
type methodname(parameter-list)
{
method-body;
}
8
Contd.
Method declaration has four parts:
i. The name of the method (methodname).
ii. The type of the value the method returns (type).
iii. A list of parameters (parameter-list).
iv. The body of the method
The type specifies the type value the method would return. This
could be a simple data type such as int as well as any class type.
It could be void type, if the method does not return any value.
The methodname is a valid identifier.
The parameter-list is always enclosed in parenthesis and
contains variable names and types of all the values we want to
give to the method as input.
9
Contd.
Methods which act upon instance variables of a class are called
instance methods.
Instance variable is a variable whose separate copy is available
in every object.
Any modifications to instance variable in one object will not
affect the instance variable of other objects. These variables are
created on heap.
Instance methods can read and act upon static variables also.
10
Class - Example
class Rectangle
{
int length, width;
void getData(int x, int y) // A method with two parameter
{
length=x;
width=y;
}
int rectArea() // A method with no parameter
{
return length*width;
}
}
11
Creating Objects
An object in Java is essentially a block of memory that contains
space to store all the instance variables.
Creating an object also known as instantiating an object.
Objects in Java are created using the new operator.
The new operator creates an object of the specified class and
returns a reference to that object.
Syntax for object creation:
classname objectname; //declares a variable to hold the object reference
objectname = new classname( ); // Assigns the object reference to the
variable
12
Contd.
Example:
Rectangle R1 = new Rectangle();
R1 is a reference to Rectangle
Rectangle object object
13
Accessing class Members
To access members (fields and the methods) of an object, use the
dot (.) operator together with the reference to an object.
The general syntax is as follows:
objectname.variablename;
objectname.methodname(parameter-list);
Example:
R1.length=23;
a) R1.width=13;
System.out.println(“Area is “+R1.rectArea();
R1.getData(34,15);
b) System.out.println(“Area is “+ R1.rectArea();
14
Complete Example
class Student
{ int studid;
String studname;
void display( )
{ System.out.println(" Student id: "+studid);
System.out.println(" Student Name: "+studname);
}
}
class StudentDemo
{ public static void main(String args[])
{ Student s1 = new Student( );
s1.studid = 1201;
s1.studname = “WCU";
s1.display();
Student s2 = new Student( );
s2.studid = 1202;
s2.studname = "ASTU";
s2.display();
}
}
15
Static Methods
Static methods can read and act upon static variables.
Static methods cannot read and act upon instance variables.
Static variable is a variable whose single copy is shared by all
the objects.
Static methods are declared using keyword static.
Static methods can be called using
objectname.methodname (or)
classname.methodname
From any object, if static variable is modified it affects all the
objects. Static variables are stored on method area.
16
Static Methods - Example
//static method accessing static variable
class Sample
{ static int x = 10;
static void display( )
{ x++;
System.out.println (" x value is = " + x);
}
}
class SDemo
{ public static void main(String args[])
{ System.out.print(“Calling static method using Class name:“);
Sample.display ();
Sample s1 = new Sample ( );
System.out.print(“Calling static method using Object name:“);
s1.display ();
}
}
17
Constructors
It is possible to initialize objects, they are created by:
Using the dot operator
19
Types of Constructors
1. Default constructor: is the type of constructor with out any
argument.
2. Parameterized Constructor: is a constructor with one or more
argument.
When an instance of an object is created then the instance will call
the constructor.
It will be the default constructor which will be called, if there are
no any parameterized constructor.
But if there is any parameterized constructor, then it will be the
parameterized constructor with the specified parameter(s) which
will be called.
20
Default Constructor
class Box
{
double width;
double height;
double depth;
Box() // default constructor
{
System.out.println("Constructing Box");
width = 10; height = 10; depth = 10;
}
double volume()
{
return width * height * depth;
}
}
21
Parameterized Constructor - Example
class Box
{
double width;
double height;
double depth;
Box(double w, double h, double d)
{
width = w; height = h; depth = d;
}
double volume()
{ return width * height * depth;
}
}
22
this Keyword
Can be used by any object to refer to itself in any
class method
Typically used to
avoid variable name collisions
pass the receiver as an argument
chain constructors
class LightSwitch
{
boolean on;
LightSwitch() {
this.on = true; //(same as on=true;)
}
LightSwitch(boolean on) {
this.on = on;
}
} 23
Cascading Constructors
A constructor can call another constructor with
this(arguments)
class LightSwitch
{
boolean on;
LightSwitch() {
this(true);
}
LightSwitch(boolean on) {
this.on = on;
}
}
24
Apple Example
class Apple {
String color;
double price;
Apple(double price) {
this("green", price);
}
25
Apple Quiz
What will these lines print out?
Apple a = new Apple("red", 100.0);
red
System.out.println(a.getColor());
100.0
System.out.println(a.getPrice());
a.setPrice(50.5);
50.5
System.out.println(a.getPrice());
27
Access Specifiers
An access specifier is a keyword that represents how to access a
member of a class. There are four access specifiers in java.
public: keyword applied to a class, makes it available/visible
everywhere. Applied to a method or variable, completely visible.
private: private fields or methods for a class only visible within that
class. Private members are not visible within subclasses, and are not
inherited.
protected: protected members of a class are visible within the class,
subclasses and also within all classes that are in the same package as that
class.
default (if no access specifier specified): it behaves like public in its
package and private in other packages.
28
Visibility - Example
public class Circle
{
private double x, y, r;
// Constructor
public Circle (double x, double y, double r)
{
this.x = x;
this.y = y;
this.r = r;
}
//Methods to return circumference and area
public double circumference() { return 2*3.14*r;}
public double area() { return 3.14 * r * r; }
}
29
Method Overloading
It is legal for a class to have two or more methods with the
same name.
However, Java has to be able to uniquely associate the
invocation of a method with its definition relying on the number
and types of arguments.
Therefore the same-named methods must be distinguished:
by the number of arguments, or
by the types of arguments
By the sequence of arguments
Method overloading is resolved at compile time.
Overloading and inheritance are two ways to implement
polymorphism.
30
Contd.
There is a difference in the no. of parameters.
void add (int a, int b)
void add (int a, int b, int c)
31
Method Overloading - Example
class Sample
{
void add(int a,int b)
{
System.out.println ("sum of two="+ (a+b));
}
void add(int a,int b,int c)
{
System.out.println ("sum of three="+ (a+b+c));
}
}
class OverLoad
{
public static void main(String[] args)
{ Sample s=new Sample ( );
s.add (20, 25);
s.add (20, 25, 30);
}
}
32
Constructor Overloading
class Box
{
double width, height, depth;
Box(double w, double h, double d)
{
width = w; height = h; depth = d;
}
Box()
{
width = -1; height = -1; depth = -1;
}
Box(double len)
{
width = height = depth = len;
}
double volume()
{ return width * height * depth;
}
}
33
Garbage Collection
Generally memory is allocated to objects by using ‘new’
operator and deleted by ‘delete’ operator in C++.
But this deletion of allocated memory works automatically in
Java.
Garbage collection is a mechanism to remove objects from
memory when they are no longer needed (unused memory).
Garbage collection is carried out by the garbage collector, gc( ):
The garbage collector keeps track of how many references an object
has.
It removes an object from memory when it has no longer any
references.
Thereafter, the memory occupied by the object can be allocated again.
The garbage collector invokes the finalize method.
34
finalize() Method
A constructor helps to initialize an object just after it
has been created.
In contrast, the finalize method is invoked just before
the object is destroyed.
The Java runtime calls that method whenever it is
about to recycle an object of that class:
protected void finalize()
{
// finalization code here
}
35
Example
class garbage extends Object class gc
{ {
int x,y; public static void main(String
void setdata(int a,int b) a[])
{ {
x=a; garbage obj1=new garbage();
y=b; garbage obj2=new garbage();
} obj1.setdata(10,20);
void display() obj1.display();
{ obj2=null;
System.out.println(“x="+x); System.gc();
System.out.println("y="+y); //obj2.display();
}
protected void finalize() }
{ }
System.out.println("
finalize");
}
}
36