Introduction to Object Orientation
Object orientation provides a new paradigm (pattern) for software
construction. In this new paradigm, objects and classes are the building
blocks, while methods, messages and inheritance produce the primary mechanisms.
Object-oriented programming is a
programming method that combines data and instructions into a self-sufficient
"object". In an object-oriented program, the design is represented by
objects. Objects have two sections, properties (instance variables) and behavior
(methods). Properties represent the current state of an object. Methods
represent how an object is used. These properties and methods are closely tied
to the real world characteristics and use of the object. An object is used by
means of its methods.
What is an Object?
Definition: Objects are discrete unit of software
bundle of data and related methods. Software objects are modeled on the basis
of real world objects which have certain characteristics and behavior. For
example Man object has characteristics like height, weight, color, etc.. The
behavior can be man is talking, walking, eating, sleeping etc…
What is a Class?
Definition: A class is a template or prototype that defines the variables and
the methods common to all objects of a certain kind.
Classes provide modularity
and structure in an object-oriented computer program
The characteristics of an object are represented as variable in a
class. Such variables are also called as instance variables. If the programmer
does not initialize the instance variables when the object is created, then
system initializes them to their respective initial values based on their data
type.
The method defined in class represents the behavior of the object.
Object-oriented
programming (OOP) is a programming paradigm (pattern) that uses "objects" to design applications
and computer programs. It utilizes several techniques from previously
established paradigms, including encapsulation, inheritance and polymorphism.
Principles of Object
Orientation
Encapsulation is the
ability of an object to place a boundary around its properties (i.e.
data) and methods (i.e. operations). Class is the basis of
encapsulation. Programs written in older languages suffered from side effects
where variables sometimes had their contents changed or reused in unexpected
ways. Encapsulation is one of three programming principles in Object Oriented Programming
languages
Inheritance is the process of an object acquiring the properties (i.e. data)
and methods (i.e. operations) from an already existing object. It is
the means of sharing properties and methods between classes based on their
hierarchy.
The advantage of using inheritance is
code reuse ability hence saving coding time, compilation time, debugging time
and testing time.
With inheritance, new classes can be derived from existing
classes, using the existing classes as building blocks. The new class inherits
properties and methods from the base class. The new class can also add its own
properties and methods.
In the above figure there exist a
class called Vehicle which has general characteristics and behavior and when we define class Car or Bike we need not
redefine these characteristics as the can be used from the parent class and we
can as well define new characteristics and behavior for Car and Bike class
Polymorphism is the
ability to interact with different type of objects by passing same message. The
client invokes the same method to interact with the different types of objects
and behavior depends on the type of the object.
For e.g. a Vehicle can be of type Car
or Bike. The way we interact with either of the mentioned objects would be
through the same methods.
Writing our own classes and using them
|
class Point
{
int x;
int y;
}
|
class PointDemo
{
public static void main(String
args[])
{
Point p;
p = new Point();
p.x = 10;
p.y = 10;
System.out.println(“p.x =
”+p.x);
System.out.println(“p.y =
”+p.y);
}
}
|
Note: The above code creates a class Point having two instance
variables x & y. Every Point has its memory allocation to hold instance
variables. Hence each Point type of object can have different values for x
& y (since they are different entities).
Point p; implies p is a reference variable of type Point
and can refer to object of class Point. [The size of the reference variable
depends upon the size of the address bus. For example, on a Java Virtual
Machine (JVM) for 32 bit Operating System, the size of reference
variable is 32 bits but it is not guaranteed].
p = new Point ();
In Java, objects can be created with
the usage of keyword new. This
statement creates an object of class Point and this object can now be accessed
with its reference which is available in variable ‘p’. Object creation means
memory allocation to the instance variables. Each time an object is created of
class Point x & y are allocated memory on the heap.
When an object is created all the instance
variables are allocated memory in heap as a single unit and are initialized by
the system to their respective initial values based on data type if not
initialized by the programmer.
The objects are accessible with the
help of reference variables only and we can never get direct access to the
object once created.
|
class PointDemo
{
Point p1 = new Point();
Point p2 = new Point();
p1.x = 12;
p1.y = 12;
p2 = p1;
System.out.println (“p1.x = ” +
p1.x);
System.out.println (“p1.y = ” +
p1.y);
System.out.println (“p2.x = ” +
p2.x);
System.out.println (“p2.y = ” +
p2.y);
}
|
Output:
p1.x = 12
p1.y = 12
p2.x = 12
p2.y = 12
|
p1 and p2 are two reference variables
of type Point referring to two different
instance of class Point. Later, when we assign p2 = p1; it means p2 hold reference of the same object which p1 is
referring to. Since both the reference variables are referring to same object
if we set p1.x = 18; then System.out.println(p2.x); results in 18 only.
|
class PointDemo
{
Point p1 = null;
p1.x = 12;
p1.y = 12;
System.out.println(“p1.x =
”+p1.x);
System.out.println(“p1.y =
”+p1.y);
}
|
Output:
This code compiles but will be a
runtime failure because p1 is not
referring to any object So there doesn’t exists x and y which are accessible
with reference variable p1.
|
‘null’ is a reference literal (constant) used in
Java to represent a void reference i.e. a reference to nothing. ‘null’ can be assigned to any reference
variable.
Note: It is also the initial value for the
reference variables which are declared in a class.
The above code compiles because the compiler will just verify the references and objects will be
created at runtime. So when we
say Point p1 = null; what compiler checks is that whether p1 can refer to null
or not. and when we say p1.x = 12; the compiler checks whether p1 is
initialized and the type represented by p1 has x or not. Remember that the
object will be created only at runtime. Since p1 is not referring to any object
there does not exits x & y which can be accessed using reference p1. Hence
attempt to access them at runtime result is NullPointerException.
Writing Methods in a Class
Class behaviors are represented in
Java by methods. To declare a method use the following syntax
|
[ "public" | "private" |
"protected" ]
[ "final" ]
[ "static" | "abstract" | "native"
]
return_data_type
method_name "(" [parameter_list] ")"
"{"
// some defining actions
"}"
|
The return_data_type
defines the type of value that the calling routine receives from the object. It
can be any of the primitive types or reference type or the reserved word void
if no message is to be returned. The statement return
variablename; is
used to declare the value to be returned to the calling routine.
The parameter list can
contain from zero to many entries of datatype variablename pairs. Entries are separated by comma (,).
Parameters are passed by value, thus upholding the encapsulation
principle by not allowing unexpected changes or side effects. Object references
(such as arrays) can also be passed
The method name and parameter name follow the camel notation for
naming convention, in which if a name has more than one word then first words
first character must be lower case and all subsequent words first character be upper
case. for example methName.
Accessor (or
observer) methods read property (i.e. field variable) values and are
conventionally named getX() or whatever the property is called.
Mutator (or
transformer) methods set property values and are often named setX()
etc. Mutators can be used to ensure that the property's value is valid in both
range and type.
It is good
programming practice to include accessor and mutator methods
for each property in the class. They are perfect example of object encapsulization.
The exceptions to writing accessor/mutator methods for each property is for
those that are used only within the class itself or for properties that are set
in more complex ways.
Helper
methods are those routines that are useful within the class
methods but not outside the class. They can help in code modularization.
Normally they are assigned private access to restrict use.
|
class Point
{
int x;
int y;
void show()
{
System.out.println(“x = ” + x);
System.out.println(“y = ” + y);
}
int getX()
{
return x;
}
int getY()
{
return y;
}
} |
class PointDemo
{
public static void main(String args[])
{
Point p = new Point();
p.x = 12;
p.y = 12;
p.show();
}
}
Output
x = 12
y = 12
|
The above code declares a show
behavior which shows the values of x
& y properties of object Point
represented by reference variable p. Such
methods are also called as accessor method.
int getX() methods returns the value of
instance variable x for the
object using whose reference we will be calling the method. For example if we
say p.getX() then this method returns
the value of x for the object
represented by reference variable p. Similarly p.getY() returns value of instance variable y for the object represented by reference variable p.
|
class Point
{
int x;
int y;
…// Code as given in above Point class
void setX(int a)
{
x = a;
}
void setY(int b)
{
y = b;
}
void set(int a, int b)
{
x = a;
y = b;
}
}
|
class PointDemo
{
public static void main(String args[])
{
Point p = new Point();
p.set(10,10);
p.show();
}
}
|
|
Output:
x = 10
y = 10
|
These method sets the value of instance variables x and y for the object represented by reference variable p.
|
class Point
{
int x;
int y;
…// Code as given in above Point class
void setX(int a)
{
x = a;
}
void setY(int b)
{
y = b;
}
void set(int x, int y)
{
x = x;
y = y;
}
}
|
class PointDemo
{
public static void main(String args[])
{
Point p = new Point();
p.set(10,10);
p.show();
}
}
|
|
Output:
x = 0
y = 0
|
The local variable and instance variable can have same name. The
above code complies but does not sets the value for the instance variables x
& y. Because compiler is not able to distinguish between local variable and
instance variable having same name. Such ambiguity is resolved with the help of
keyword ‘this’. Then the instance variable are accessed with the help of
keyword ‘this’ where’ this’ is the
object reference which refers to the object of the class using whose reference
we will be accessing the method in which ‘this’
is used.
Usage of keyword this becomes
implicit when there no ambiguity between local variables and instance variable.
Note: Reference of ‘this’
is final and this will always refer to the object using whose reference we call
the method in which ‘this’ is used.
|
class Point
{
int x;
int y;
…// Code as given in above Point class
void setX(int
a) // Sets the value
for instance variable x
{
x = a;
}
void setY(int b) // Sets the value for instance variable y
{
y = b;
}
void set(int x, int y)
{
this.x = x;
this.y = y;
}
}
|
class PointDemo
{
public static void
main(String args[])
{
Point p = new
Point();
p.set(10,10);
p.show();
}
}
|
|
Output:
x = 10
y = 10
|
Exercise
1. Write a class for creating an object of
Bank Account which has properties like accounted, name, currentBalance etc and
has behavior like withdraw() and deposit() apart from having accessor methods
and mutator methods.
2. Write a class called Man which has
properties like name, height, weight etc. and has behavior like walk(), talk(),
eat() etc.
No comments:
Post a Comment