Download as pdf or txt
Download as pdf or txt
You are on page 1of 64

D1.

OOP
OBJECTS AS A PROGRAMMING CONCEPT

DINESH KUMAR PRABHURAJ


OBJECT

• It has two components: –


• data (also called states) which can be variables or data structures likes arrays/lists
• actions (also called behaviours) which can be functions/procedures (methods in Java)
OBJECT VS CLASS

• Object – refers to a particular instance of a class,


where the object can be a combination of
variables or data structures (called states) and
functions, procedures or methods (called
behaviours)
• Class – an extensible program-code-template for
creating objects, providing initial values for states
(variables) and implementations of behaviours
(functions/procedures/methods)
CLASS VS OBJECT
CLASS
OBJECT AND INSTANTIATION

• In Java, an OBJECT is an INSTANCE of a CLASS. We can make lots of OBJECTS from the
same CLASS. Each OBJECT requires some memory to store it's details. Each OBJECT
has it's own copy of its VARIABLES and its own copy of the class METHODS.
• But, if the METHODS or VARIABLES are STATIC, then there is only one copy of the
method or variable, and all the OBJECTS share the same copy .
STEPS IN OBJECT CREATION

• A class provides the blueprints for objects.


• An object is created from a class.
• In Java, the new key word is used to create new objects.
• There are three steps when creating an object from a class:
• Declaration: A variable declaration with a variable name with an object type.
• Instantiation: The 'new' key word is used to create the object.
• Initialization: The 'new' keyword is followed by a call to a constructor. This call
initializes the new object.
Every time you create a new instantiation,
EXAMPLE:OBJECT another section of RAM is zoned off for all
the states that might be recorded in that
object, whether they have data in or not.

• From the example you can see, you can call a Constructor method with no parameter values being
given. In that case, the object would be created with whatever default values are stated in the
constructor method that has no parameters. There can be, and often is, more than one
constructor in every class template.
JAVA’S IMPLEMENTATION OF OOP

• Rather confusingly, Java called both classes and objects a


“class”
• To make matters “even more interesting” we can
differentiate between different types of Java classes by what
they do.
• For example, in every Java project, there can be multiple
object-classes (templates for making new objects that will
essentially contain data), but only ONE class that contains
the ‘main’ method.
• The class that contains the ‘main’ method is referred to as
the driver class (and there can be only ONE in each project)
OBJECTS USES RAM

• Every time a new object is instantiated from a base


class, a space equivalent to the WHOLE object is
reserved in RAM.
• Depending on the number of states in the object, a
lot of RAM can be wasted / reserved but not used.
Therefore, it is best to use the most memory
efficient variable types.
VARIABLE IN RAM VS. OBJECT IN RAM

• The more RAM being used by a program,


the more processor time is needed to
read/write/process the data. The more
processor cycles being used, the more
‘sluggish’ the computer would be to the
user.
Basic point:More RAM used = slower response
EXAMPLE
CLASS DIAGRAM
ASSOCIATIONS

• As projects contain multiple classes (driver & providers), it is important to show the relationship
between two objects.

• This is a basic example where class A1 (driver) has a main method in which an object of class B1
(provider) is instantiated.
MULTIPLE CLASS DIAGRAMS IN ONE PROJECT
INTERPRET UML DIAGRAMS

UML Class diagram ---→ Java code


class Person
Person {
private String name;
-name:String
private cup item;
-item:cup
private boolean fatigue;
-fatigue:boolean
public cup getCup()
+getCup():cup {
+setName(n:String):void return item;
}
public void setName(String n)
{
name=n;
}
}
class student
{
private String name;
private String[] sarray; JAVA CODE → UML CLASS
protected int idnumber;
DIAGRAM
student()
{
name="none"; student
sarray={"Eng", "Mat", "CompSci"};
idnumber=940643; -name:String
} -sarray:String []
#Idnumber:int
public String[] getSubjects()
{ student()
return sarray; +getSubjects():String []
} +setID(i:int):void

public void setID(int i)


{
idnumber=i;
}
}
EXERCISE
DECOMPOSITION
DECOMPOSITION

A library rents out


audio books on CD to
members.
They employ 18 staff
members .
We decompose objects to understand how they work. A complex object is made up of many simpler
objects. The simpler objects are easier to understand.
Describe the process of decomposition
into several related objects
Decomposition means
"breaking down" into
component parts. Employee

Administrative Faculty Maintenance

Principal Secretary
All of the people who work at your
school are employees. But there are
different types of employee, so we can
decompose employee.
PRACTICE WITH THESE

• Employers
• Traffic simulation model

• Calculator
• Calendar

• Media Collections
RELATIONSHIPS

• Four types of relationships


• Dependency – “uses”
• Aggregation – “has a”
• Inheritance – “is a”
• Association – “uses”

Is Inheritance A Lotus Esprit is a car


Has Composition/Aggregation A smartphone has a CPU
Uses Dependency A project manager uses a Gantt Chart
COMPARISION

• Association is the most generic relationship. The other three are more specific and are used in
particular situations.
DEPENDENCY

• We use a dependency relationship to show when one element depends on another element.
• It points from the independent entity to the dependent entity in the system.

• This is a unidirectional kind of relationship between two objects.

• In the figure below, an object of Player class is dependent (or “uses”) an object of Bat class.
ASSOCIATION

• Association is relation between two separate classes which establishes through their Objects.
• Association can be one-to-one, one-to-many, many-to-one, many-to-many.

• In Object-Oriented programming, an Object communicates to other Object to use functionality and


services provided by that object.
• Aggregation is a particular type of Association.
class Bank class Employee
{ {
private String name; private String name;
Employee(String name)
Bank(String name) { class Association
{ {
this.name=name;
this.name=name; public static void
}
} main(String args[])
public String public String {
getBankName() getEmployeeName() Bank b=new Bank("ICICI");
{ { Employee e=new
return this.name; Employee("Devid");
return this.name;
System.out.println(e.getE
} } mployeeName()+ " is employee of "
} } +b.getBankName());
}
}

Java Program

Example- Association
ASSOCIATION VS DEPENDENCY

• Association and dependency are often confused in their usage.


• There are a large number of dependencies in a system.

• We only represent the ones which are essential to convey for understanding the system.
• We need to understand that every association implies a dependency itself.
• However, we prefer not to draw it separately.
AGGREGATION

• It is a special form of Association where:


• It represents “has a” relationship.
• It is a unidirectional association i.e. a one way relationship.
For example, department can have students but vice versa is not possible and thus
unidirectional in nature.
• In Aggregation, both the entries can survive individually which means ending one entity will
not effect the other entity
import java.util.*;
class Student
class Department
{
{
String name;
String name;
int id;
private List<Student> students;
String dept;
Department(String name,List<Student>
Student(String name,int id,String dept)
students)
{
{
this.name=name;
this.name=name;
this.id=id;
this.students=students;
this.dept=dept;
}
}
public List<Student> getStudents()
}
{
return students;
}
}

Java Program Example- Aggregation


class Aggreration
class Institute {
public static void main(String []args)
{ {
String instituteName; Student s1=new Student("Devid",1,"EEE");
private List<Department> departments; Student s2=new Student("Mathew",1,"ECE");
Institute(String Student s3=new Student("John",2,"EEE");
Student s4=new Student("Priya",1,"CS");
instituteName,List<Department> departments)
{ List <Student> eee_students=new ArrayList<Student>();
this.instituteName=instituteName; eee_students.add(s1);
eee_students.add(s3);
this.departments=departments;
} List <Student> ece_students=new ArrayList<Student>();
public int getTotalStudentsInstitute() ece_students.add(s2);
{
List <Student> cs_students=new ArrayList<Student>();
int noOfStudents=0; cs_students.add(s4);
List<Student> students;
for(Department dept : departments) Department eee=new Department("EEE",eee_students);
Department ece=new Department("ECE",ece_students);
{
Department cs=new Department("CS",cs_students);
students=dept.getStudents();
for(Student s : students) List<Department> departments=new ArrayList<Department>();
{ departments.add(eee);
departments.add(ece);
noOfStudents++; departments.add(cs);
}
} Institute institute=new Institute("Oakridge", departments);
return noOfStudents;
System.out.print("Total Students in Institute: ");
} System.out.print(institute.getTotalStudentsInstitute());
} }
}
INHERITANCE

• Inheritance is the mechanism by which one class is allow to inherit the features (states
and behaviours) of another class.
• Super Class: The class whose features are inherited is known as super class (or a base
class or a parent class).
• Sub Class: The class that inherits the other class is known as sub class (or a derived class,
extended class, or child class). The subclass can add its own states and behaviours in
addition to the superclass states and behaviours.
class Bicycle //Base Class class MountainBike extends Bicycle //Derived
{ class
public int gear; {
public int speed; public int seatHeight;
public Bicycle(int gear,int speed) public MountainBike(int gear,int speed,int
{ startHeight)
this.gear=gear;
{
this.speed=speed;
} super(gear,speed);
public void applyBrake(int decrement) seatHeight=startHeight;
{ }
speed-=decrement; public void setHeight(int newValue)
} {
public void speedUp(int increment) seatHeight=newValue;
{ }
speed+=increment;
public String toString()
}
public String toString() {
{ return(super.toString()+"\nseat height
return ("No of gears are is "+seatHeight);
"+gear+"\n"+"speed of bicycle is "+speed); }
} }
}

Java Program Example- Inheritance


public class inheritance
{
public static void main(String []args)
{
MountainBike mb=new MountainBike(3,100,25);
System.out.println(mb.toString());
}
}
Multiplicity Meaning Example

1 Exactly Vehicle has one engine


one
MULTIPLICITY
0…1 Zero or Pet has zero or one
one owner
0…* Zero or Hotel has 0 or many
Many customers
1…* One or Customer has one or
many many orders
IDENTIFY THE
RELATIONSHIP
EX: PASSENGER RESERVATION SYSTEM

• A Booking is always for exactly one


passenger:
– Cannot have a booking without a passenger.
– A booking could never involve more than one
passenger.
• A Passenger can have any number of Bookings:
– A passenger could have no bookings at all.
– A passenger could have more than one
booking.
NEED TO REDUCE DEPENDENCIES BETWEEN OBJECTS IN A GIVEN PROBLEM

• Dependency? Why so bad?


• It increases maintenance overheads
• Maintenance overheads refer to the
changes that need to be made to the
entire system if you make a change to
a component.
• For example if you change, B, it affects
how C, D and E works, implying that
you have to spend time fixing them to
work with the “new” B.
IMAGINE THE CHANGES NEEDED!

• How much maintenance would it create if


you change the Customers’ Details class?
• How much maintenance would it create if
you change the Transactions class?
Outline the need to reduce dependencies between objects in a
given problem.

• Two classes are said to form a dependency if I think I'm going to


a change to one of them necessitates a change change my Linked List
in the other. class around a bit.…
• On large software projects this can cause
significant problems.
• This is also known as high coupling.
• Decoupling is desirable and is what every
software developer strives for.
• Encapsulation is one of many ways to reduce
coupling. Aarrgh! My software uses
• Most of the others are beyond the IB syllabus, that class. If you change
such as the use of Interfaces, factory it, my software might not
patterns and dependency injections. work any more!
CONSTRUCTING RELATED OBJECTS

• You work for a music shop:Take Note


• It has two types of employees: managers and
office staff

• The managers have all the same states as the


office staff, but an additional ‘responsibility’ state
• The TakeNote driver class has two linked lists:
one of managers and another of office staff
• Construct a UML class diagram to show the
relationships between these classes
Explain the need for different data
types to represent data items.

All data stored on a


computer system is
ultimately just sequences of But computers can do sums
bits, like 11010010 with negative numbers and
decimals, so there must be
minus signs and decimal
points too?

Nope. There are only bits. So how do computers do it?


Come to think of it, aren't
you reading text on a
computer right now? How
can all data be just bits??
Explain the need for different data
types to represent data items.

All data are just sequences


of bits, but the way those
bits are interpreted gives
them different meanings.
Go on…

The bits I gave you earlier,


11010010, could mean 210,
-46, "Ò" or even
2.942726775082115848939 So I guess it's pretty
83212491E-43, depending important to make it clear
on how they are interpreted. exactly which data type
you're using!
DIFFERENT DATA TYPES

• integer (Java: int), e.g. 3, -4, 999, 23

• real (Java: double), e.g. -3.1415, 9.999


• String (Java: String) e.g. “strange”

• Boolean (Java: boolean) e.g. true / false


WHY DO WE NEED DIFFERENT TYPES?

• Data is stored as a combination of binary values in the computer.

• Data types are used to store different kinds of data.


• They are needed because they specify to the computer how to interpret the binary
values in the storage.
IS ONE TYPE BETTER THAN ANOTHER?

• Each data type (in Java) takes up a different amount of RAM:


• Boolean = 1 byte
• Integer = 4 bytes
• Real = 8 bytes
• String = … a lot!
• multiply the number of characters of the String by two;
• add 38;
• if the result is not a multiple of 8, round up to the next multiple of 8;
• E.g. “I love cheese” = 12 character x 2 = 24 + 38 = 62 → 64 bytes
THE LESS RAM A PROGRAM USES, THE MORE EFFICIENT IT IS LIKELY TO BE.
Explain the need for different data
types to represent data items.

▪ Opposite is one of lots of ways of encoding text on a computer


▪ It's a table of numbers and their corresponding characters
▪ Look back at the previous example and you will see from the table
that 11010010 = 210 = "Ò"
▪ But where are the Korean characters, the Cyrillic characters, the
Arabic characters??
▪ This scheme uses 8 bits and therefore only encode for 28 different
characters
▪ Modern systems, such as Unicode, use as many as 16 or 32 bits.
32 bits gives you 232 = 4,294,967,296 different possible characters!
▪ This is another reason we need to specify data types – they take up
varying amounts of space
PARAMETERS

• Parameters allow us to pass information or instructions into functions and procedures.


• Parameters are the names of the information that we want to use in a function or
procedure.
• The values passed in are called arguments.
PARAMETER

method mult (a):


for loop x from 1 to 5
output a*x

end loop
end method

a is a parameter - it allows us to pass a value into the procedure for it to use. Running the following
code would create a multiplication table of 50 up to 5.
multi(50)
The 50 here is called the argument - because it is a value passed in.
parameter
PARAMETER VS ARGUMENT

public void sum(int x, int y)


{
System.out.println(x+y);
}
public static void main(String []args)
{
Test t=new Test();
t.sum(10,20);
}

argument
DECLARING METHODS IN JAVA
No input parameter,
but function returns a value

No input
parameter,
no return
value – void

Takes input parameter,


and function returns a value
JAVA IS STRICTLY “PASS BY VALUE”!

• Consider the following Java program that passes a primitive type to function.
public class test
{
public static void main(String []args)
{
int x=5;
change(x);
System.out.println(x);
}
public static void change(int x)
{
x=10; OUTPUT ?
}
}
• We pass an int to the method change() and as a result the change
in the value of that integer is not reflected in the main method.
• Java creates a copy of the variable being passed in the method and then
do the manipulations.
• Hence the change is not reflected in the main method.
D1.10 Describe how data items can be
passed to and from actions as parameters.
Passing primitives
▪ We try to add one to i within the method
addOneToThisInt but it doesn't work
▪ Outside the method, the value of i is unchanged
▪ This is because i itself is not passed to the
method, only a copy of i's value
▪ We can change the copy as much as we like, but
the original i doesn't get changed
▪ Analogy: You want access to an important
document that is locked within my filing cabinet. I
make a photocopy of it and give it to you. You can
tear it up, burn it, whatever you like, but my copy
is safe.
▪ (The way to change i's value is to return the
changed variable, and assign the return value to i,
as in returnThisIntWithOneAdded)
Describe how data items can be passed to
and from actions as parameters.
Passing object references
▪ This time we pass to the method a reference to an
object and try to change the object
▪ The object's id gets changed, both inside the method
and outside!
▪ Analogy: You want access to an important document
that is locked within my filing cabinet. I give you the
key to the filing cabinet. If you change the document,
you have changed the only copy.
▪ Some people mistakenly think that this means that
Java is both pass by value (primitives) and pass by
reference (objects)
▪ See the next slide for the truth…
Describe how data items can be passed to
and from actions as parameters.
The truth about Java
▪ Like before we pass to the method a reference to
an object, but this time we try to change the
reference itself by making it point to a totally
different object!
▪ This fails. The reference outside the method still
points to the original object
▪ Analogy: You want access to an important
document that is locked within my filing cabinet. I
give you a copy of the key to the filing cabinet. If
you change the document, you have changed the
only copy, but if you try to re-grind the key (or
something), you have not changed my key.
▪ Hence, whether primitives are passed or object
references are passed, Java is always pass by
value.
Describe how data items can be passed to
and from actions as parameters.
▪ This is an advanced point for
teachers, that may help with fielding
a difficult question from students… ▪ Compare this with the "passing object
references" slide
▪ String is an object type, but you can't change the
object by passing its reference to a method!?
▪ This is because it is an immutable type
▪ Java provides a few immutable types for very
common object types such as String and the
primitive wrapper classes
▪ In fact, it is recommended by software design
gurus that you should always make your classes
immutable where possible
▪ Not providing any setter methods is one way of
doing this!
←Huh?!
REFERENCES

You might also like