4. OOP in Java - Part - 1
4. OOP in Java - Part - 1
Two Paradigms
All computer programs consist of two elements: code and data.
some programs are written around “what is happening” - process-
oriented model - a program as a series of linear steps
and others are written around “who is being affected.” - object-
oriented programming - a program around its data (that is,
objects) and a set of well-defined interfaces to that data
These are the two paradigms that govern how a program
is constructed.
An object-oriented program can be characterized as
data controlling access to code
2
Object Oriented Programming Principles
The Three OOP Principles
Encapsulation: mechanism that binds together code and the data it
manipulates, and keeps both safe from outside interference and misuse.
the basis of encapsulation is the class
Inheritance: process by which one object acquires the properties of
another object, which supports the concept of hierarchical classification.
inherit its general attributes from its parent
Inheritance interacts with encapsulation as well.
If a given class encapsulates some attributes, then any subclass will have the same
attributes plus any that it adds as part of its specialization.
This is a key concept that lets object-oriented programs grow in complexity
linearly
rather than geometrically.
A new subclass inherits all of the attributes of all of its ancestors.
Polymorphism: (from Greek, meaning “many forms”) is a feature
that allows one interface to be used for a general class of actions.
often expressed by the phrase “one interface, multiple methods.” 3
A Sample Program This is a comment.
4
A Sample Program
5
A Sample Program
6
A Sample Program
The public keyword is an access modifier, which allows the programmer to
control the visibility of class members. When a class member is preceded
by public, then that member may be accessed by code outside the class
7
A Sample Program
The keyword static allows main( ) to be called without
having to instantiate a particular instance of the class. This is necessary
since main( ) is called by the Java Virtual Machine before any objects are
made.
8
A Sample Program
The keyword void simply tells the compiler that main( ) does not return a
value.
9
A Sample Program
main( ) is the method called when a Java application
begins
10
A Sample Program
Command Line
Arguments
11
Introduction to Classes
class is the core of Java.
It is the logical construct upon
which the entire Java language is
built because it defines the shape
and nature of an object.
As such, the class forms the basis
for object-oriented programming in
Java.
Any concept you wish to implement
in a Java program must be
encapsulated within a class.
Class it defines a new data type.
Once defined, this new type can be
used to create objects of that type.
Thus, a class is a template for an
object, and an object is an instance
of a class.
12
Classes
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.
Instance variables are acted upon and
accessed by the methods defined for that
class. Thus, as a general rule, it is the methods
that determine how a class’ data can be used.
Variables defined within a class are called
instance variables because each instance of the
class (that is, each object of the class) contains
its own copy of these variables.
Thus, the data for one object is separate and
unique from the data for another.
the general form of a class does not specify
a main( ) method
13
A Simple Class - Box
Box that defines three instance variables: width,
height, and depth.
Currently, Box does not contain any methods
a class defines a new type of data. In this case, the new
data type is called Box.
You will use this name to declare objects of type Box
To actually create a Box object, you will use a statement
like the following:
Box mybox;
mybox = new Box();
After this statement executes, mybox will refer to
an instance of Box.
Every Box object you create, will contain its own Object.variable
copies of the instance variables width, height, and depth
To access these variables, you will use the dot (.) operator
mybox.width = 100;
18
Declaring Objects
19
Declaring Objects
obtaining objects of a
class is a two-step
process. First, you must
declare a variable of the
class type
20
The new operator dynamically allocates memory
for an object and returns a reference to it. This
reference is the address in memory of the object
allocated by new.
21
Declaring Objects
Box mybox; // declare reference to object
mybox = new Box(); // allocate a Box object
22
Declaring Objects
23
Assigning Object Reference Variables
Box b1 = new Box();
Box b2 = b1;
26
Adding a Method That Takes Parameters
It is important to keep the two terms parameter and argument straight.
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.
27
Adding a Method That Takes Parameters
Dimensions of each box had to be set separately by use of a sequence
of statements, such as:
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
While this code works, it is troubling for two reasons. First, it is clumsy
and error prone. For example, it would be easy to forget to set a dimension.
Second, in well-designed Java programs, instance variables should be
accessed
only through methods defined by their class.
In the future, you can change the behavior of a method, but you can’t
change the behavior of an exposed instance variable.
28
29
different ways to create an object in
Java
30
Anonymous object
Anonymous simply means nameless.
An object which has no reference is known as an anonymous object.
It can be used at the time of object creation only.
If you have to use an object only once, an anonymous object is a good
approach.
For example:
new Calculation();//anonymous object
Calling method through a reference:
Calculation c=new
Calculation() c.fact(5);
Calling method through an
anonymous object
new Calculation().fact(5);
31
Anonymous object
class Calculation{
void fact(int n)
{ int fact=1;
for(int
i=1;i<=n;i++){
fact=fact*i;
}
System.out.printl
n("factorial is
"+fact);
}
public static void
main(String
args[]){
new
Calculation().fact 32
Creating multiple objects by one type
only
Multiple objects can be created by one type only as similar to the primitives.
Initialization of primitive variables:
int a=10, b=20;
Initialization of refernce variables:
Rectangle r1=new Rectangle(), r2=new Rectangle();//creating two objects
33
Creating multiple objects by one type
only
class Rectangle{
int length;
int width;
void insert(int l,int w){
length=l;
width=w;
}
void calculateArea(){System.out.println(length*width);}
}
34
Creating multiple objects by one type
only
class TestRectangle2{
public static void main(String args[]){
Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}
35
Object and Object reference
The objects are created in the heap area and, the reference obj just points
out to the object of the class in the heap, i.e. it just holds the memory
address of the object (in the heap).
In short, object is an instance of a class and reference (variable) points out to
the object created in the heap area.
36
Ways to initialize object
Initializing an object means storing data into the object.
There are 3 ways to initialize object in Java.
By reference variable
By method
By constructor
38
Object and Class Example: Initialization
through reference
class Student{
int id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
s1.id=101;
s1.name="Sonoo";
System.out.println(s1.id+"
"+s1.name);//printing members
with a white space
}
}
39
Object and Class Example: Initialization
through reference
class Student{
int id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
s1.id=101;
s1.name="Sonoo";
System.out.println(s1.id+"
"+s1.name);//printing members
with a white space
}
}
40
Object and Class Example: Initialization
through method
class Student{
int rollno;
String name;
void
insertRecord(i
nt r, String n){
rollno=r;
name=n;
}
void
displayInforma
tion(){
System.out.pri
ntln(rollno+"
"+name);
} 41
Object and Class Example: Initialization
through method
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}
42
Constructors
It can be tedious to initialize all of the variables in a class each time
an instance is created
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 look a little strange because they have no return type, not
even void.
This is because 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 creating an instance will have a fully initialized, usable object
immediately.
43
44
45
Object and Class Example: Initialization
through a constructor
46
Default Constructor
When you do not explicitly define a constructor for a class,
then Java creates a default constructor for the class.
This is why the preceding line of code worked in earlier
versions of Box that did not define a constructor.
When using the default constructor, all non-initialized instance
variables will have their default values, which are zero, null,
and false, for numeric types, reference types, and boolean,
respectively.
The default constructor is often sufficient for simple classes,
but it usually won’t do for more sophisticated ones.
Once you define your own constructor, the default constructor is
no longer used.
47
Parameterized Constructors
48
49
Method Overloading and Polymorphism
Method overloading supports polymorphism because it is one way that
Java implements the “one interface, multiple methods” paradigm.
To understand how, consider the languages that do not support method
overloading, each method must be given a unique name.
However, frequently you will want to implement essentially the same
method for different types of data.
Consider the absolute value function.
In languages that do not support overloading, there are usually three or
more versions of this function, each with a slightly different name.
50
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 this is the case, the methods are said to be overloaded, and the
process is referred to as method overloading
Method overloading is one of the ways that Java supports polymorphism
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
While overloaded methods may have different return types, the return
type
alone is insufficient to distinguish two versions of a method
51
52
Overloading
In some cases,
Java’s
automatic type
conversions
can play a role
in overload
resolution
53
Overloading Constructors
In addition to overloading normal
methods, you can also overload
constructor methods.
In fact, for most real-world classes
that you create, overloaded
constructors will be the norm, not the
exception
the Box( ) constructor requires three
parameters.
This means that all declarations of
Box objects must pass three
arguments to the Box( ) constructor.
For example, the following statement
is currently invalid:
Box ob = new Box();
54
Overloading Constructors
55
Overloading Constructors
56
Instance Variable Hiding
It is illegal in Java to declare two local variables with the same name
inside the same or enclosing scopes.
Interestingly, you can have local variables, including 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
this lets you refer directly to the object, you can use it to resolve any
namespace collisions that might occur between instance variables and
local variables
57
The this Keyword
Sometimes a method will need to refer to the object that invoked it.
To allow this, Java defines the this keyword. this can be used inside any
method to refer to the current object.
That is, this is always a reference to the object on which the method
was invoked.
You can use this anywhere a reference to an object of the current class’
type is
permitted.
This version of Box( ) operates exactly like the earlier version.
The use of this is redundant, but perfectly correct and is useful in
other contexts
Inside Box( ), this will always refer to the invoking object
58
this keyword
There can be a lot of usage of Java this keyword.
In Java, this is a reference variable that refers to the current
object.
Usage of Java this keyword
this can be used to refer current class instance variable.
this can be used to invoke current class method (implicitly)
this() can be used to invoke current class constructor.
this can be passed as an argument in the method call.
this can be passed as argument in the constructor call.
this can be used to return the current class instance from the method.
59
this keyword
// this: to refer current class instance variable
class Student{
int rollno;
String name;
float fee;
Student(int
rollno,String
name,float
fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display()
{System.out.printl
n(rollno+"
"+name+" "+fee);}
}
class TestThis2{
public
}} static void main(String args[]) 38
this keyword
// this: to invoke current class method
class A{
void m(){System.out.println("hello m");}
void n()
{ System.out.println("hello
n");
//m();//same as this.m()
this.m();
}
}
class TestThis4{
public static void main(String args[]){
A a=new A();
a.n();
}}
61
this keyword
// this: to invoke current class constructor
class A{
A(){System.out.println("hello a");}
A(int x){
this();
System.out.println(x);
}
}
class TestThis5{
public static void main(String args[]){
A a=new A(10);
}}
62
this keyword
64
this keyword
// this: to pass as argument in the constructor call
class
B{ A4
obj;
B(A4
obj){
this.ob
j=obj;
}
void
display
(){
System
.out.p
rintln(
obj.d
ata);/
/
using
data
mem
65
Objects as Parameters
66
Objects as Parameters
67
Objects as Parameters
68
Argument Passing
Two ways to pass an argument to a subroutine
call-by-value: copies the value of an argument into the formal parameter of
is passed to the parameter, this reference is used to access the actual argument
specified in the call
This means that changes made to the parameter will affect the argument used
to call the subroutine
Java uses call-by-value to pass all arguments, the precise effect differs
Thus, a copy of the argument is made, and what occurs to the parameter
69
Argument Passing
When you pass an object to a method, objects are passed by call-by-reference
Keep in mind that when you create a variable of a class type, you are only
creating a reference to an object
Thus, when you pass this reference to a method, the parameter that
receives it will refer to the same object as that referred to by the argument
This effectively means that objects act as if they are passed to methods by
use
of call-by-reference
Changes to the object inside the method do affect the object used
as an argument
70
Argument Passing
71
Returning Objects
72
Adding Two Points (x, y coordinates) Using Object as Parameter and
Returning Object
Array of Objects
Class_Name[ ] objectArrayReference;
Student[] students; (or) Student students[];
2. Instantiation: After declaring the array, instantiate it using the new keyword,
specifying the size of the array.
77