You are on page 1of 35

Object-Oriented

Programming
What is Object-Oriented Programming?

•A set of implementation techniques that:


–can be done in any programming language
–may be very difficult to do in some
programming languages
•A strong reflection of software engineering
–abstract data types
–information hiding (encapsulation)
What is Object-Oriented Programming?

•A way of encouraging code reuse


–produces more malleable systems
•A way of keeping the programmer in touch with the
problem
–real world objects and actions match program
objects and actions
Terms normally associated with OOP
• abstraction
• encapsulation
• information hiding
• inheritance
• polymorphism
Abstraction
• Functions – Write an algorithm once to be used in
many situations
• Objects – Group a related set of attributes and
behaviors into a class
• Frameworks and APIs – Large groups of objects that
support a complex activity.
 Frameworks can be used “as is” or be modified to
extend the basic behavior.
OO in Java
•Language elements:
> Class-based object-oriented programming
language with inheritance
> A class is a template that defines how an object
will look and behave once instantiated
•Java supports both instance and class (static)
variables and methods
•Nearly everything is an object
•Objects are accessed via references
•Object behavior can be exposed via public
methods
•Objects are instantiated using the new construct
Classes Classes
•A class defines the
characteristics
of similar objects
– a specification
•Objects of the same class are
similar with respect to:
– Interface
– Behavior
– State space (set of
possible
states, and state
transitions)
•Classes are used to instantiate
specific objects (each with
Class
• most fundamental aspect of object-oriented
programming
• template or prototype that defines a type of object
• a blueprint from which an object is actually made
• describes the state or the data that each object
contains
• describes the behavior that each object exhibits
• classes in Java support three key features of OOP:
 Encapsulation
 Inheritance
public class MyPoint {
// attributes
private int x;
private int y;
// methods
public void setX(int n) {
x = n; }
public void setY(int n) {
y = n; }
public int getX() {
return x; }
public int getY() {
return y; }
public void display() {
System.out.println("(" + x + "," + y + ")");
}}
• In the MyPoint class, x and y are called
data members, instance variables or
attributes
• setX(int n), setY(int n), getX(), geY()
and display() are called methods
Object
• instance of a class
• in order to create an instance from a class
definition, use the new keyword
MyPoint p = new MyPoint();
p is a reference variable

x:0
Point
p y:0 Object
Objects
•An object possesses:
– Identity
a means of distinguishing
it
from other objects
– State
what the object
remembers
– Interface •Objects are:
what messages the – Building blocks for
object systems
responds to – Identifiable abstractions
– Behavior of
what the object can do real world objects
Instance variables or attributes
• define the state of an object in a class.
• can also be objects.
Methods
• functions that provide processing to the
object’s data.
• determine the behavior of an object.
• The collection of all publicly available
methods is called the class
interface.
Message and Object Communication
•Objects communicate via messages
•Interfaces define the set of valid messages that an
object can receive
•Messages, in Java, correspond to method calls
(invocations)
•Senders need a reference to the target object to send a
message
Accessing State
•State information can be accessed directly or by
using
messages
•Using messages:
–eliminates the dependence on implementation
–allows the developer to hide the details of the
underlying implementation
•“Accessor” messages are usually used instead of
accessing state directly
–example: getSpeed() may simply access a
state value called “speed” – or it could hide (or later
be replaced by) a calculation to obtain the same
value
Encapsulation
• Hides the implementation details of a class
• Forces the user to use an interface to access data
• Makes the code more maintainable
Accessing Object Members
• The dot notation: <object>.<member>
• to access the members of the class, use the dot
operator
p.setX(20);
p.display();
• the dot operator is used to access object members
including attributes and methods
• Examples:
obj1.setNum (47);
obj1.num = 47; //only allowed if x is public
Example of bad class Client code can access data
design: members directly:

class MyTime {
MyTime time1 = new MyTime();
public int seconds;
public int minutes; time1.seconds = 70; //no checking
public int hour;
time1.minutes = 70; // no checking
}
A better design:
Client code can access data
class MyTime { members directly:
private int seconds;
private int minutes; MyTime time1 = new MyTime();
private int hour; time1.setSeconds(70);
public void setSeconds(int sec) //error will be handled in the
{ // method
if ((sec >= 0) && (sec <=59))
seconds = sec;
else
// error handling code
}
Constructors
• A constructor is a method that is automatically
invoked when an object is created. It is normally
used to initialize data members.
• It has the same name as the name of the class. It
can receive parameters but it has no return value
• Example
public class MyPoint {
private int x;
private int y;
// constructor
public MyPoint (int a,int b) {
x = a; y = b;
}
Default Constructor
• If the programmer did not provide any constructor,
a default no-argument constructor is automatically
provided.
 The default constructor takes no arguments
 The default constructor has no body
• Enables the user to create object instances with new
Xxx() without having to write a constructor
• If the programmer writes a constructor, the default
constructor is not anymore provided.
Constructing and initializing objects
Calling new ...() causes the following events to
occur:
• memory is allocated for the new object and instance
variables are initialized to their default values
• explicit attribute initialization is performed
• the appropriate constructor is executed
Declaring
MyPoint p;
allocates space only for the reference. No object is
created unless the new operator is invoked.

MyPoint p = new MyPoint(10,20);


MyPoint q =p;
q.setX(50);
p.display(); // displays (50,20)
• In the MyPoint class, in the method display(), which x
and y values are displayed? They are the x and y
values of the object which invoked display.
Example:
MyPoint p = new MyPoint(20,20);
p.display();
--> the x and y values of the object referenced by
p is displayed.
The this reference
• How does display know that it is the x and y values of
the object referenced by p that is supposed to be
displayed?
• When a method is invoked by an object, the object
reference is implicitly transmitted as a hidden first
argument to the method. Inside the method, the
reference has a name and it is called this.
public class MyPoint {
private int x;
private int y;
public MyPoint(int x,int y) {
this.x = x;
this.y = y;
}
}
Method Overloading
• Java allows the definition of two or more methods
with the same name within the same class provided
that the order and type of parameters are different.
Example:
class Dummy {
public void display() {
}
public void display(int x) {
}
public void display(int x,char ch) {
}
}
Overloading Constructors

public class MyPoint {


private int x;
private int y;

public MyPoint(int x,int y) {


this.x = x;
this.y = y;
}
public MyPoint() {
this(0,0);
}
}
Package Statement

• allows for the grouping of classes


• should be placed before any class or any import
statement.
• corresponds to a directory structure

package mypackage;

public class MyPoint {


}
import Statement
• in order to specify the specific package/directory where
the classes to be used in the class are located, use the
import statement
• should be placed after the package statement but
before any class definition

import mypackage;

public class UsePoint {


}
nheritance

is used to :
a. factor common attributes and methods in superclass
b. extend existing classes to support new abstractions
c. represent problem domain abstractions more accurately

Defining an inheritance hierarchy has several useful


advantages :
a. organizes classes
b. eliminates redundancy of definitions
c. simplifies specialization
d. facilitates code reuse
Inheritance (continued)

Inheritance Example :

Generalization BankAccount

Specialization SavingsAccount CheckingAccount

- Superclass contains attributes and methods applicable to


all subclass instance.
Inheritance
Person

Employee Student

Teacher Doctor
Method Overriding
• The method name that is used in the
parent class can also be used in the child
class.
• If the method has different number and
type of parameters, it is still overloading, but
if the method has exactly the same signature,
it is called overriding.
• Overriding provides a way to redefine a
method in the parent class.
The Object Class
- the root of all classes in Java
- any class that is created automatically
“extends” the Object class.
- the Object class includes certain useful
methods which can be
overridden by any class. Some of the
useful methods are:
public boolean equals(Object obj);
- returns true if obj is equal to this object

public String toString();


- returns a string representation of the
object

You might also like