0% found this document useful (0 votes)
2 views

attachment-1

This document provides an overview of Object-Oriented Programming (OOP), distinguishing it from procedural programming and outlining key concepts such as classes, objects, encapsulation, and inheritance. It discusses the advantages of OOP, including portability, security, and abstraction, and explains the structure of Java programs, including identifiers, data members, methods, and access modifiers. Additionally, it covers control statements, loops, and the significance of constructors and static members in Java.

Uploaded by

yerosanabraham83
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

attachment-1

This document provides an overview of Object-Oriented Programming (OOP), distinguishing it from procedural programming and outlining key concepts such as classes, objects, encapsulation, and inheritance. It discusses the advantages of OOP, including portability, security, and abstraction, and explains the structure of Java programs, including identifiers, data members, methods, and access modifiers. Additionally, it covers control statements, loops, and the significance of constructors and static members in Java.

Uploaded by

yerosanabraham83
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 92

OBJECT ORIENTED PROGRAMMING

(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

the program from the operations that manipulate


the data.
 The unit in object-oriented programming is class.

 Object-oriented programming starts from isolating

the classes, and then look for the methods inside


them.
 Object-oriented programming focus on both of
2
them.
CONT…D

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

world that can be distinctly identified.


 For example, a student, a desk, a circle and a

button can all be viewed as objects.


 An object has a unique identity, state and

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

and interpreted by virtual Machine (JVM) on


whichever platform it is being run.
 Secure: it enables to develop virus-free,

tamper-free systems. Authentication


techniques are based on public-key
encryption.
6
CONT…
 The ability to download applets with
confidence that no harm will be done and
that no security will be breached is the most
innovative aspect of Java.
 Portable: Being architectural-neutral and

having no implementation dependent


aspects of the specification makes Java
portable

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

relevant data to the user.


 i.e: The client cares about what functionality

a car offers, not about how that functionality


is implemented.

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

 Information is stored within the object


 It is hidden from the outside world

 It can only be manipulated by the method

declared inside the object itself


 Eg. My name is stored within my brain. You

can’t access my name directly, rather you


can ask me to tell my name.

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

 Must begin with a letter of the alphabet, a dollar sign ($), or

the underscore (_) character


 Java is case sensitive
 Public isn’t the same as public

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

Data type variable = value;

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

the console window /standard output window.


 We display data, results or messages to the console

window via System.out.


 The System class includes a number of useful class

data values. One is an instance of the PrintStream


class named out.

20
SYNTAX
 System.out.print("Hello, Dr. Caffeine.");
 The println method will skip to the next line after

printing out its argument.

21
STANDARD INPUT
 System.in accepts input from the keyboard.
 Using System.in for input is slightly more

complicated than using System.out for output.


 System.in is an instance of the InputStream class

that provides only a facility to input 1 byte at a time


with its read method.
 However, multiple bytes are required to represent

common types of data such as strings. The Scanner


class from the java.util package provides a
necessary input facility to accommodate various
input routines. To input data from the standard
input by using a Scanner object, we first create it
by passing System.in as follows:
22
CONT…D
import java.util.*;
...
Scanner input = new Scanner(System.in);
variable11 = input.nextType();

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.

 Object is an instance of a class. Each


object has a class which defines its data
and behavior

25
CONDITIONAL STATEMENTS
 The if Statement:
 The if...else Statement:

 The if...else if...else Statement:

 An if can have zero or one else's and it must

come after any else if's.


 An if can have zero to many else if's and they

must come before the else.


 Once an else if succeeds, none of the

remaining else if's or else's will be tested.

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

times a task is to be repeated.


 Syntax:

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

need to loop through. The expression can be


an array variable or method call that returns
an array.

32
CONT…D
 Nested if...else Statement
 The switch Statement: A switch statement

allows a variable to be tested for equality against


a list of values. Each value is called a case, and
the variable being switched on is checked for each
case.

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

a switch. Each case is followed by the value to be


compared to and a colon.
 The value for a case must be the same data type as

the variable in the switch and it must be a constant


or a literal.
 When the variable being switched on is equal to a

case, the statements following that case will execute


until a break statement is reached.

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

appears, the flow of control will fall through to


subsequent cases until a break is reached.
 A switch statement can have an optional default

case, which must appear at the end of the switch.


 The default case can be used for performing a task

when none of the cases is true. No break is needed in


the default case.

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

internal state of an object and the object to-object


communication is done via methods.
 Class - A class can be defined as template/blue print

that describes the behaviors/states that object of its


type support.

37
Class declaration

Begins with the reserved word class followed by the name(any


valid identifier ) may be preceded with the accessibility modifier
class Bicycle {
//data members
//constructors
//methods
}

38
DATA MEMBERS
 Are the data values associated with the class or
instances of the class.
 syntax for the data member declaration <modifier-

list> <data type> <name> ;


 Where <modifier-list> designates different

characteristics of the data member,


 <data type> the class name or primitive data type,

and
 <name> the name of the data member(its value

changes via time)

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

never include a return statement.


 The modifier of a constructor does not have to be

public, but non-public constructors are rarely used.

41
OBJECT DECLARATION

 The definition of the class does not create any


objects.
 It is objects that participate in program operations.

 An object declaration designates the name of an

object and the class to which the object belongs. Its


syntax is
 <class name> <object names> ;

42
CONT…D
 No objects are actually created by the declaration.
 We create an object by invoking the new operator.

 Memory space will be given for an object,

 If space is not used then de-allocate it, and the

mechanism to de-allocate unused space is called


garbage collection.

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

 Limited to the package only

 Only classes inside the package can access a class or

method defined as 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

can be used by itself, without reference to a


specific instance.
 To create such a member, precede its declaration

with the keyword static.


 When a member is declared static, it can be

accessed before any objects of its class are


created, and without reference to any object.

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:

<class name> . <class data members>

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

define a separate main class.

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

shown (+ for public access and – for private access).


 Attributes are normally being kept private and

methods normally made public.

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:

 programs will be made up of many classes

 classes will relate to each other.

 relationships are shown by arrows, (inheritance and

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

returns a boolean value. Fully


SOLUTION

64
DENOTING RELATIONSHIPS
 Association

describes the connection between


different classes (the connection
between the actual objects is called
object connection, or link.

65
CONT…D

can be uni- or bidirectional


has a role and a multiplicity
value, which dictates how
many objects on this side of
the association can relate to
66

one object on the other side.


CONT…D
 Multiplicity is the number of objects involved in an
association
 Is displayed as a range [min..max] of non-negative

values, with a star (*) on the maximum side


representing infinite.
 Attributes could be primitive data type;

 Attributes can also be objects as defined by other

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

other is known as subclass (derived class,


child class) and the class whose properties
are inherited is known as superclass (base
class, parent class). 73
CONT…D
a subclass can refer to items defined in its
superclass, but not vice versa.
Inheritance is not limited to one level.
A subclass can be a superclass of other
classes, forming an inheritance hierarchy.

74
CONT…D

75
CONT…D

 The idea behind inheritance in java is that


we can create new classes that are built
upon existing classes.
 When we inherit from an existing class, we

can reuse methods and fields of parent


class, and we can add new methods and
fields also.

76
WHY INHERITANCE ?
 For Method Overriding: runtime polymorphism can be
achieved.
 For Code Reusability.

 With the use of the extends keyword, the subclasses

will be able to inherit all the properties of the


superclass except for the private properties of the
superclass.
Syntax
class Super{
.....}
class Sub extends Super{
77
..... }
EXAMPLE
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary
is:"+p.salary);
System.out.println("Bonus of Programmer 78

is:"+p.bonus);
EXAMPLE
class Calculation{
int z;

public void addition(int x, int y){


z = x+y;
System.out.println("The sum of the given
numbers:"+z);
}
public void Substraction(int x,int y){
z = x-y;
System.out.println("The difference between the 79
given numbers:"+z);
} }
CONT…D
public class My_Calculation extends Calculation{
public void multiplication(int x, int y){
z = x*y;
System.out.println("The product of the given
numbers:"+z);
}
public static void main(String args[]){
int a = 20, b = 10;
My_Calculation demo = new My_Calculation();
demo.addition(a, b);
demo.Substraction(a, b);
80
demo.multiplication(a, b);
}}
EXAMPLE DEMONSTRATION
 In the given program, when an object to My_Calculation
class is created, a copy of the contents of the
superclass is made within it. That is why, using the
object of the subclass you can access the members of a
superclass.

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

of the superclass, we need to use the super


keyword viz:
 super(values);

……

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:

public interface Animal {


}
public class Mammal implements Animal{
}
public class Dog extends Mammal{
88
}
THE INSTANCEOF KEYWORD
 Used to determine whether Mammal is actually an
Animal, and dog is actually an Animal
Example: evaluate the result of
the code.
interface Animal{ }
class Mammal implements Animal{ }
public class Dog extends Mammal{

public static void main(String args[]){


Mammal m = new Mammal();
Dog d = new Dog();
System.out.println(m instanceof Animal); 89
System.out.println(d instanceof Mammal);
System.out.println(d instanceof Animal); }}
HAS-A RELATIONSHIP
 These relationships are mainly based on the usage.
 This determines whether a certain class HAS-A

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:

class BB extends AA,CC{


//invalid in java
}
 However, a class can implement one or more

interfaces, which helped Java get rid of the


impossibility of multiple inheritance

92

You might also like