attachment-1
attachment-1
(OOP)
BY WUBISHET GIRMA.
1
PROCEDURAL VS. OBJECT-ORIENTED
PROGRAMMING
The unit in procedural programming is function.
Procedural programming concentrates on creating
functions.
Procedural programming separates the data of
3
WHAT IS OOP?
• To have a fine definition of OOP,
Please note what you are showing in
your class room now?
4
CONT…D
Object-oriented programming (OOP) involves
programming using objects.
An object represents an entity in the real
behaviors.
5
ADVANTAGES OF OOP
Platform independent: when compiled, it
is not compiled into platform specific
machine, rather into platform independent
byte code
This byte code is distributed over the web
7
HOW’S OOP PORTABLE?
8
CONCEPTS OF OBJECT-ORIENTED PROGRAMMING
9
ABSTRACTION
Abstraction is simplifying complex reality by
modeling classes appropriate to the problem.
Abstraction is a mechanism to show only
10
ENCAPSULATION
Encapsulation allows the programmer to
group data and the methods that operate on
them together in one place, and to hide
details from the user.
11
BENEFITS OF ENCAPSULATION
Encapsulation protects the integrity of an
object's data.
Protects an object from unwanted access by
clients.
Allows you to change the class
implementation.
Allows you to constrain objects' state
12
ABSTRACTION VS ENCAPSULATION
13
ADVANTAGES OF ENCAPSULATION
Simplicity and clarity
Low complexity
Better understanding
14
INHERITANCE & POLYMORPHISM
This will be visited in chapter 3 and 4
respectively
15
INFORMATION HIDING
16
IDENTIFIERS AND THEIR
DECLARATION
Names used for classes, variables and methods
are called identifiers. A variable provides us with
named storage that our programs can be
manipulated.
Name of a class, method, or variable
Can be any length
Can include any character except a space
17
JAVA DEVELOPMENT ENVIRONMENT
How to set java development environment?
To be covered on lab session.
18
CONT…
A keyword cannot be used as an identifier.
Most importantly, identifiers are case
sensitive.
Eg. age, $salary, _value, __1_value
Syntax
19
Standard input/ output
When a program computes a result, we need a way
to display this result to the user.
One of the most common ways to do this is to use
20
SYNTAX
System.out.print("Hello, Dr. Caffeine.");
The println method will skip to the next line after
21
STANDARD INPUT
System.in accepts input from the keyboard.
Using System.in for input is slightly more
23
The Java Program Structure
/*
This is a simple Java program.
Call this file "Example.java".
*/
class Example {
// Your program begins with a call to main().
public static void main(String args[]) {
System.out.println("This is a simple Java program.");
}
}
24
CONCEPT OF CLASS AND OBJECT
Class refers to a blueprint of an object. It
defines the variables and methods the
objects support.
25
CONDITIONAL STATEMENTS
The if Statement:
The if...else Statement:
26
LOOP CONTROLS
There may be a situation when we need to
execute a block of code several number of
times and is often referred to as a loop.
Java looping mechanisms:
1. while Loop
2. do...while Loop
3. for Loop
27
WHILE LOOP
Is a control structure that allows you to
repeat a task a certain number of times.
Syntax:
while(Boolean_expression)
{
//Statements
}
28
THE DO...WHILE LOOP:
A do...while loop is similar to a while loop,
except that a do...while loop is guaranteed to
execute at least one time.
Syntax:
do {
//Statements }
while(Boolean_expression);
29
THE FOR LOOP:
Is a repetition control structure that allows
you to efficiently write a loop that needs to
execute a specific number of times.
A for loop is useful when you know how many
for(initialization;Boolean_expression; update)
{
//Statements
}
30
ENHANCED FOR LOOP IN JAVA:
mainly used for Arrays.
Syntax:
for(declaration : expression)
{
//Statements
}
31
CONT…D
Declaration: The newly declared block
variable, which is of a type compatible with
the elements of the array you are accessing.
Expression: This evaluates to the array you
32
CONT…D
Nested if...else Statement
The switch Statement: A switch statement
33
RULES FOR SWITCH
The variable used in a switch statement can only be
a byte, short, int, or char.
You can have any number of case statements within
34
CONT…D
When a break statement is reached, the switch
terminates, and the flow of control jumps to the next
line following the switch statement.
Not every case needs to contain a break. If no break
35
JUMP STATEMENTS
Break
continue and
return
36
LECTURE II
Object - Objects have states and behaviors.
It‘s state is stored in fields and behavior is shown via
methods.
In software development, methods operate on the
37
Class declaration
38
DATA MEMBERS
Are the data values associated with the class or
instances of the class.
syntax for the data member declaration <modifier-
and
<name> the name of the data member(its value
39
METHODS
The syntax for defining a method is the following
<modifiers> <return type> <method name>
( <parameters> ) {
<statements>
}
40
CONSTRUCTOR
Is a special method that is executed when a new
instance of the class is created, that is, when the
new operator is called.
public <class name> ( <parameters> ) {
<statements>
}
It doesn’t have a return type, consequently, will
41
OBJECT DECLARATION
42
CONT…D
No objects are actually created by the declaration.
We create an object by invoking the new operator.
43
MESSAGE SENDING
After the object is created, we can start sending
messages to it.
<object name> . <method name> ( <arguments> ) ;
44
ACCESS MODIFIERS
Restricts the access of a class, constructor, data
member and method in another class.
Types of modifiers:
Default access modifiers:
When no modifier is written its assumed to be default
45
PRIVATE MODIFIER
Limited to a class only
Private data members and methods are accessible
only within a class
Class and interface can’t be declared as private
if a class has private constructor then we can’t
create an object of that class from outside of the class
46
PROTECTED ACCESS
Protected data members and methods are accessible
only by the classes of the same package and the
subclasses present in any package
Used in parent-child relationship
47
PUBLIC MODIFIERS
No restriction at all
Can access everywhere
48
THE FINAL KEYWORD
A variable can be declared as final. Doing so
prevents its contents from being modified.
A final method prevents overriding and a final class
prevents inheritance.
This means that you must initialize a final variable
when it is declared.
49
THE STATIC KEYWORD
A class member must be accessed only in
conjunction with an object of its class.
However, it is possible to create a member that
50
CALLING METHODS OF THE SAME CLASS
whenever we called a method of some object, we used
dot notation, such as acct.deduct(12).
It is possible to call a method from a method of the
same object.
51
DIFFERENCE
52
CLASS CONSTANTS
A class constant will be shared by all methods of the
class.
class AccountVer3 { import java.text.*;
// Data Members class DeductionWithFee {
private static final double FEE = 0.50; //This sample program deducts money
private String ownerName; // three times from the account
private double balance; public static void main(String[] args) {
//Constructor DecimalFormat df = new DecimalFormat("0.00");
public AccountVer3(String name, double startingBalance) { AccountVer3 acct;
ownerName = name; acct = new AccountVer3("Carl Smith", 50.00);
balance = startingBalance; acct.deduct(10);
} acct.deduct(10);
//Deducts the passed amount from the balance acct.deduct(10);
public void deduct(double amt) { System.out.println("Owner: " +
balance = balance - amt - FEE; acct.getOwnerName());
} System.out.println("Bal : $"
//other methods are exactly the same as before, so + df.format(acct.getCurrentBalance()));
//we will omit them here } 53
} }
PUBLIC CONSTANTS
We may want to declare certain types of class
constants as public
Exception:
a constant is “read only” by its nature, so it won’t
have a negative impact if we declare it as public
a constant is a clean way to make certain
characteristics of the instances known to the client
programs.
class data members are accessed by the syntax:
54
LOCAL VARIABLES
defined inside methods, constructors or blocks.
Declared and initialized within the method
destroyed when the method has completed.
55
Changing Any Class to a Main Class
it is possible to define the main method to a class so
the class becomes the main class of a program also.
we have one less class to manage if we don’t have to
56
class Bicycle {
HOW?
private String ownerName; // Data
Member
public String getOwnerName( ) {//Returns the
name of this bicycle's owner
return ownerName; }
public void setOwnerName(String name)
{//Assigns the name of this bicycle's owner
ownerName = name; }
public static void main(String[] args) { //main
method
Bicycle myBike;
myBike = new Bicycle( ); 57
myBike.setOwnerName("Jon Java");
System.out.println(myBike.getOwnerName() +
THE UML CLASS DIAGRAM
Shows multiple classes and how they are related to
each other. Shows architecture of the system.
A class diagram consists of a unique name
(conventionally started with capital letter), a list of
attributes (int, double, boolean, String) and a list of
methods.
For attributes and methods, the visibility modifiers are
58
EG
Draw the UML class diagram to represent a class
called “BankAccount” with attribute balance (of
type int) and methods depositMoney() and
withdrawMoney(). Show the appropriate visibility
modifiers.
59
SOLUTION
60
CONT…D
UML allows us to suppress any information we do not
wish to highlight in our diagrams.
Allows us to suppress irrelevant detail.
In java:
aggregation relationships).
61
UML SYNTAX
The syntax for attribute is:
visibility name: type
where the visibility is one of the following.
+ stands for public attributes
# stands for protected attributes
- stands for private attributes
Syntax for methods :
Visibility name (para1:type1, par2:type2):
return type
62
EG.
Draw a diagram to represent a
class called “BankAccount” with
private attribute balance with
type int and public method
depositMoney() which takes an
integer parameter ,’deposit’ and
63
64
DENOTING RELATIONSHIPS
Association
65
CONT…D
class
67
UML MULTIPLICITY SYMBOL TABLE
Symbol Meaning
1 One
* Some (0 to infinity
)
0..1 None or one
1..* One or more
2..4 Two, three or four
68
EX
Draw a diagram to represent a class called
“Catalogue” and a class called
“ItemForSale” as defined below. ItemForSale
has an attribute ‘name’ of type String and an
attribute ‘price’ of type int. it also has a
method setPrice() which takes an integer
parameter ‘newPrice’. ‘Catalogue’ has an
attribute ‘listOfItems’ i.e the items currently
held in the catalogue. As zero or more items
can be stored in the catalogue, ‘lisOfItems’ will
need an array or collection. “Catalogue” also
has a method addItem() which takes an ‘item’
as a parameter (of type ItemForSale) and adds 69
this item to the ‘listOfItems’. Draw this on class
diagram showing appropriate visibility
SOLUTION
70
EXAMPLE
public class Lamp { class ClassObjectsExample
private boolean isOn; {
Public void turnOn() { public static void
main(String[] args) {
isOn = true; }
Lamp l1 = new Lamp(),
public void turnOff() l2 = new l1.turnOn();
{ l2.turnOff Lamp();
isOn = false; } ();
void l1.displayLightStatus();
displayLightStatus() { l2.displayLightStatus();
}}
System.out.println("Ligh
71
t on? " + isOn);
}}
CLARIFICATION
Here, we defined a class named Lamp.
The class has one instance variable (variable defined inside
class) isOn and two methods turnOn() and turnOff(). These
variables and methods defined within a class are called
members of the class.
Notice two keywords, private and public in the above program.
These are access modifiers which will be discussed in detail in
later chapters. For now, just remember:
• The private keyword makes instance variables and
methods private which can be accessed only from inside the
same class.
• The public keyword makes instance variables and
methods public which can be accessed from outside of the class.
In the above program, isOn variable is private whereas turnOn()
and turnOff() methods are public. 72
If you try to access private members from outside of the class,
compiler throws error.
LECTURE 3
INHERITANCE
A mechanism in which one object acquires all
the properties and behaviors of parent
object.
Information is made manageable in a
hierarchical order.
The class which inherits the properties of
74
CONT…D
75
CONT…D
76
WHY INHERITANCE ?
For Method Overriding: runtime polymorphism can be
achieved.
For Code Reusability.
is:"+p.bonus);
EXAMPLE
class Calculation{
int z;
81
CONT…D
A subclass inherits all the members (fields, methods,
and nested classes) from its superclass.
The Superclass reference variable can hold the subclass
object, but using that variable you can access only the
members of the superclass, so to access the members
of both classes it is recommended to always create
reference variable to the subclass.
82
THE SUPER KEYWORD
It is used to differentiate the members of
superclass from the members of subclass, if they
have same names.
It is used to invoke the superclass constructor
from subclass.
Syntax:
super.tobeaccessed;//
sub.tobeaccessed;
83
INVOKING SUPERCLASS
CONSTRUCTOR
While inheriting, the subclass automatically
acquires the default constructor of the superclass.
But if we want to call a parameterized constructor
……
84
EXAMPLE
class Superclass{
int age;
Superclass(int age){
this.age = age; }
public void getAge(){
System.out.println("The value of the variable
named age in super class is: " +age); } }
public class Subclass extends Superclass {
Subclass(int age){
super(age); }
public static void main(String argd[]){
85
Subclass s = new Subclass(24);
s.getAge(); } }
IS-A RELATIONSHIP
IS-A is a way of saying: This object is a type of that
object.
How is the extends keyword used to achieve
inheritance?
public class Animal{
}
public class Mammal extends Animal{
}
public class Reptile extends Animal{}
public class Dog extends Mammal{}
86
APPLYING IS-A RELATIONSHIP
Now, consider the IS-A relationship, on the above
example:
Mammal IS-A Animal
Reptile IS-A Animal
Dog IS-A Mammal
· Hence: Dog IS-A Animal as well
87
THE IMPLEMENTS KEYWORD
The implements keyword is used to get the IS-A
relationship
Is used with classes to inherit the properties of an
interface
Interfaces can never be extended by a class
Example:
certain thing.
This relationship helps to reduce duplication of code
as well as bugs.
90
TYPES OF INHERITANCE
91
CONT…D
Java does not support multiple inheritance
This means that a class cannot extend more than one
class
Example:
92