2. OO Programming Concepts
2
Object-oriented programming (OOP) involves
programming using objects. An object represents
an entity in the real world that can be distinctly
identified. For example, a student, a desk, a circle,
a button, and even a loan can all be viewed as
objects. An object has a unique identity, state, and
behaviors. The state of an object consists of a set
of data fields (also known as properties) with their
current values. The behavior of an object is defined
by a set of methods.
3. Objects
3
An object has both a state and behavior. The state
defines the object, and the behavior defines what
the object does.
Class Name: Circle
Data Fields:
radius is _______
Methods:
getArea
Circle Object 1
Data Fields:
radius is 10
Circle Object 2
Data Fields:
radius is 25
Circle Object 3
Data Fields:
radius is 125
A class template
Three objects of
the Circle class
4. Classes
4
Classes are constructs that define objects of the
same type. A Java class uses variables to define
data fields and methods to define behaviors.
Additionally, a class provides a special type of
methods, known as constructors, which are
invoked to construct objects from the class.
5. Classes
5
class Circle {
/** The radius of this circle */
double radius = 1.0;
/** Construct a circle object */
Circle() {
}
/** Construct a circle object */
Circle(double newRadius) {
radius = newRadius;
}
/** Return the area of this circle */
double getArea() {
return radius * radius * 3.14159;
}
}
Data field
Method
Constructors
6. Defining a class
A class is a user defined data type that serve to
define its properties .
Once the class is defined we can create
“variables” of that type using declaration that
are similar to the basic type declaration .
In java these variables are termed as instance
of the classes ,which are actual objects.
6
7. The basic form of class declaration is as below:
class classname [extends superclass]
{
[variables declarations;]
[method declarations;]
}
7
9. Adding method
The general form of method declaration is :
type mehodname (parameter list)
{
method body;
}
Method declarations has four basic parts
Method name
Returns type
Parameter list
The body of the method
9
11. class Rectangle
{
int length ;
int width ;
void getdata(int x,int y)
{
length=x;
width = y;
}
int rectArea()
{
int area = length*width;
return(area);
}
}
11
12. Creating objects
Objects in java are created using the new operator .
The new operator creates an objects of the
specified class and returns a reference to that
objects.
Ex.
Rectangle rect1; //declare
rect1 = new rectangle(); //instantiate
The method rectangle is the default constructor of
the class .we can create any no. of objects of
rectangle 12
14. class Rect
{
int length;
int width;
void getdata(int x,int y)
{
length=x;
width=y;
}
int rectArea()
{
int area=length*width;
return(area);
}
}
illustration of class and object
14
class RectangleArea
{
public static void main(String[]args)
{
int area1,area2;
Rect rect1=new Rect();
Rect rect2=new Rect();
rect1.length = 1;
rect1.width = 2;
area1=rect1.length*rect1.width;
rect2.getdata(5,10);
area2=rect2.rectArea();
System.out.println("area1="+area1);
System.out.println("area2="+area2);
}
}
15. Constructors
We know that all object that are created need initial
values.
One approach for this is the use of Dot operator
through which we access the instance variables
and then assign values to them individually
In second approach we use method like getdata to
initialize each object individually.
Java supports a special type of method called
constructor that enable an object to initialize
itself when it is created.
15
16. Replacement of getdata by a constructor method
16
class Rectangle
{
int length ;
int width ;
void getdata(int x,int y)
{
length=x;
width = y;
}
int rectArea()
{
int area = length*width;
return(area)
}
}
class Rectangle
{
int length ;
int width ;
Rectangle (int x , int y) // constructor
method
{
length=x;
width = y;
}
int rectArea()
{
int area = length*width;
}
}
17. illustration of constructors
17
class Recta
{
static int length;
static int width;
void getdata(int x,int y)
{
length=x;
width=y;
}
Recta(int x,int y)
{
length=x;
width=y;
}
Recta ()
{
}
int rectArea()
{
int area=length*width;
return(area);
}
}
class RectArea
{
public static void main(String[]args)
{
int area1,area2;
Recta rect1=new Recta();
Recta rect2=new Recta(10,20);
rect1.length = 1;
rect1.width = 2;
area1=rect1.length*rect1.width;
rect2.getdata(5,10);
area2=rect2.rectArea();
System.out.println("area1="+area1);
System.out.println("area2="+area2);
}
}
18. Difference between constructors and
methods
The important difference between
constructors and methods is that
constructors create and initialize objects that
don't exist yet, while methods perform
operations on objects that already exist.
Constructors can't be called directly; they are
called implicitly when the new keyword
creates an object. Methods can be called
directly on an object that has already been
created with new.
18
19. The definitions of constructors and methods
look similar in code. They can take
parameters, they can have modifiers
(e.g. public), and they have method bodies in
braces.
Constructors must be named with the same
name as the class name. They can't return
anything, even void (the object itself is the
implicit return).
Methods must be declared to return
something, although it can be void.
19
20. Static members
In general any class contains two sections . One declares variables and
other declares methods .these variables and methods are called
instance variables and instance methods .
This is because every time we the class is instantiated a new copy of
each of them is created .
If we want to define a member that is common to all the objects and
accessed without using a particular object .that is the member belongs
to the class as a whole rather than the object created from the class
such members are called static members .
Static variables and static methods are often referred as class variables
and class methods in order to distinguish them from their
counterparts instance variables and instance methods.
Static variables are used when we want to have a variable common to all
instance of a class.
Ex: static int count;
static int max(int x,int y)
20
21. Defining and using static members
Class mathoperation
{
static float mul(float x,float y)
{
return x*y;
}
static float divide(float x , float y)
{
return x/y;
}
}
Class mathapplication
{
public static void main(string args[])
{
float a= mathoperation.mul (4.0,5.0);
float b= mathoperation.divide(a,2.0);
System.out.println(“b=“+b);
}
} 21
22. Method overloading
In java it is possible to create methods that have
the same name ,but different parameter lists
and different definitions . This is called
overloading . Method overloading is used when
object are required to perform similar tasks but
using different input parameters.
this process is known as polymorphism.
22
24. Inheritance :extending a class
The mechanism of deriving a new class from an old one is
called inheritance . The old class is know as base class or
super class or parent class and new class is called
subclass or derived class or child class.
The inheritance allows subclass to inherit all the variable
and methods of their parent classes.
Inheritance may take different forms :
single inheritance (only one super class)
multiple inheritance (several super classes)
hierarchical inheritance (only one super class , many subclasses)
multilevel inheritance (derived from a derived class)
24
25. Defining a subclass
A subclass may be defined as follows:
class subclassname extends supreclassname
{
variable declaration;
methods declaration;
}
25
26. 26
class Room
{
int length;
int breadth;
Room (int x,int y)
{ length=x;
breadth=y;
area();
}
int area( )
{
return (length*breadth);
}
}
class BedRoom extends Room
{
int height;
BedRoom(int x,int y,int z)
{
super(x,y);
height =z;
}
int volume()
{
return(length*breadth*height);
}
}
public class InherTest
{
public static void main(String args[])
{ BedRoom room1 = new BedRoom(14,12,10);
int area1= room1.area();
int volume1=room1.volume();
System.out.println("Area="+area1);
System.out.println("Volume="+volume1);
}
}
27. Subclass constructor
A subclass constructor is used to the instance variable of
both the subclass and the super class .
The subclass constructor uses the keyword super to
invoke the constructor method of the super class .
The keyword super is subject to the following condition :
super may only be used within a subclass constructor
method.
The call to super class constructor must appear as the
first statement within the subclass constructor .
The parameter in the super call must match the order
and type of the instance variables in the super class.
27
28. Overriding methods
Method inheritance enables us to define and use method
repeatedly in subclass without having to define the
method again in subclass .
At some occasions we want an object to respond to the
same method but have different behavior when the
method is called.
This is possible by defining a method in the subclass that
has the same name ,same argument and same return
type as a method in the super class .
Then when the method is called the method defined in the
subclass is invoked and executed instead of the one in
the super class .
This is know as overriding. 28
29. 29
class Super
{
int x;
Super(int x)
{
this.x=x;
}
void display()
{
System.out.println("Super x="+x);
}
}
class Sub extends Super
{
int y ;
Sub(int x,int y)
{
super(x);
this.y=y;
}
void display()
{
System.out.println("Super x="+x);
System.out.println("Sub y="+y);
}
}
public class OverrideTest
{
public static void main(String args[])
{
Sub s1= new Sub(100,200);
s1.display();
}
}
Output:
Super x=100
Sub y=200
30. 30
The this Keyword
The this keyword is the name of a reference
that refers to an object itself. One common use
of the this keyword is reference a class’s
hidden data fields.
Another common use of the this keyword to
enable a constructor to invoke another
constructor of the same class.
31. The this keyword is the name of a reference that refers to a
calling object itself. One of its common uses is to reference a
class’s hidden data fields. For example, a data-field name is
often used as the parameter name in a set method for the data
field. In this case, the data field is hidden in the set method.
You need to reference the hidden data-field name in the
method in order to set a new value to it. A hidden static variable
can be accessed simply by using the ClassName.StaticVariable
reference. A hidden instance variable can be accessed by
using the keyword this, as shown in next example
31
32. 32
Reference the Hidden Data Fields
public class Foo {
private int i = 5;
private static double k = 0;
void setI(int i) {
this.i = i;
}
static void setK(double k) {
Foo.k = k;
}
}
Suppose that f1 and f2 are two objects of Foo.
Invoking f1.setI(10) is to execute
this.i = 10, where this refers f1
Invoking f2.setI(45) is to execute
this.i = 45, where this refers f2
33. The this keyword gives us a way to refer to the object
that invokes an instance method within the code of the
instance method. The line this.i = i means “assign the
value of parameter i to the data field i of the calling
object.” The keyword this refers to the object that
invokes the instance method set I, as shown in Figure
10.2(b). The line Foo.k = k means that the value in
parameter k is assigned to the static data field k of the
class, which is shared by all the objects of the class.
33
34. 34
Another common use of the this keyword is to enable a constructor
to invoke another constructor of the same class. For example, you
can rewrite the Circle class as follows:
35. Final variables and methods
All method and variables can be overridden by default
in subclasses . If we wish to prevent the subclasses
from overriding , we can declare them as final using
the keyword final as a modifier .
Example :
final int SIZE =100;
final void showstatus()
{
}
35
36. Final classes
Sometimes we may like to prevent a class being
further subclasses for security reasons .
A class that cannot be is called a final class . This is
achieved in java using the keywords final as
follows:
final class Aclass (…)
final class Bclass extends Someclass(…)
Declaring a class final prevent any unwanted
extension to the class.
36
37. Finalizer methods
Java supports a concept called finalization , which is
just opposite to the initialization .
The finalizer method is simply finalize( ) and can be
added to any class . java calls that method
whenever it is about to reclaim the space for that
object . The finalize method should explicitly
define the task to be performed.
37
38. Abstract classes and methods
In java we can do something which is just opposite to final that is we
can indicate that a method must always be redefined in a subclass ,
thus making overriding compulsory .
This is done using the modifier keyword abstract in the method
definition
Example:
abstract class Shape
{
…………….
…………….
abstract void draw();
………………
}
when a class contains one or more abstract method it should be declared
abstract as in above given example. 38
39. While using the abstract class we must satisfy the
following condition :
We can not use abstract classes to instantiate
object directly.
The abstract methods of an abstract class must be
define in its subclass .
We cannot declare abstract constructor or abstract
static methods.
39
40. Visibility control
Public Access
Any variable or method is visible to the entire
class in which it is defined but if we want to make
it visible to all the classes outside this class we
need to declare that variable or method as public .
Example:
public int number ;
public void sum( )
{
………….
}
40
41. Friendly access
Some times we do not use public modifier ,yet they are
still accessible in other classes in the program .
When no access modifier is specified the member
defaults to a limited version of public accessibility is
known as “friendly ” level of access .
The difference between the “public” access and the
“friendly” access is that the public modifier makes field
visible in all classes , regardless of their packages while
the friendly access makes fields visible in same package,
but not in other packages.
(A package is group of classes stored separately .)
A package in java is similar to a source file in “C”.
41
42. Protected access
The visibility level of a “protected ” field lies in
between the public access and friendly
access.
that is the protected modifier makes the field
visible not only to all classes and subclasses
in the same package but also to subclasses in
other packages .
the non-subclasses in other package cannot
access the “protected ” members.
42
43. Private access
private field enjoy the highest level degree of
protection .
They are accessible only within their own class .
They cannot be inherited by subclasses and
therefore not accessible in subclasses .
A method declares as private behaves like a method
declared as final .
It prevent the method from being sub classed .
43
44. Private protected Access
A field can be declared with two keywords private
and protected together like
private protected int x ;
this gives a visibility level in between the
“protected” access and private access .
This modifier makes the field visible in all subclasses
regardless of what package they are in .
But these fields are not accessible by other classes in
the same package .
44