0% found this document useful (0 votes)
21 views53 pages

Introduction to Object-Oriented Programming

This document provides an introduction to Object-Oriented Programming (OOP) and programming languages, outlining key concepts such as programming paradigms, machine language, assembly language, and high-level languages. It emphasizes the principles of OOP, including data encapsulation, object modeling, and the advantages of using Java as an object-oriented language. Additionally, it describes the Java development environment and the process of creating and executing Java applications.

Uploaded by

nafirom3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views53 pages

Introduction to Object-Oriented Programming

This document provides an introduction to Object-Oriented Programming (OOP) and programming languages, outlining key concepts such as programming paradigms, machine language, assembly language, and high-level languages. It emphasizes the principles of OOP, including data encapsulation, object modeling, and the advantages of using Java as an object-oriented language. Additionally, it describes the Java development environment and the process of creating and executing Java applications.

Uploaded by

nafirom3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Object Oriented Programming

Chapter One
Introduction to Object-
Oriented Programming

By: Boki C.

1 12/6/2019
Outline
o Programming Languages
o Programming Paradigm and its types
o Over View of OOP Principles
o Over View of Java Programming

2
Programming Languages (PL)
 A computer program is a set of instructions
used to operate a computer to produce a
specific result.
 Writing computer programs is called computer
programming.
 The languages used to create computer programs are
called programming languages.

How to write Program ?

3
o Programming Language
I. Is a formal constructed language designed to
communicate instructions to a machine,
particularly a computer.
II. Is used to create programs to control the
behavior of a machine
o Hundreds of computer languages are in use today.
o Programming Languages are classifies as:
I. Machine Language
II. Assembly Language
III. High Level Language

4
Machine Language
 Machine language is the “natural language” of a computer and it
is defined by its hardware design.
 Machine languages generally consist of strings of numbers (1s
and 0s) - that instruct computers to perform their most
elementary operations one at a time.
 Machine languages are machine dependent.
 Machine language program is also called object code Such
languages are difficult for humans to write a program.
 Machine-language programming was simply too slow, tedious
and error prone for most programmers.
Example
o Machine Instruction Machine Operation
00000000 Stop Program
00000001 Turn bulb fully on

5
Assembly Language
 Assembly language uses English-like abbreviations/
mnemonic codes to represent elementary operations
instead of sequence of 0s and 1s
 Example:-ADD for addition , SUB for subtraction etc.
 Translator programs called assemblers were
developed to convert assembly-language programs to
machine language Since computer system only
understand the language of 0s and 1s .
 Although such code is clear to humans, but it is not
understandable to computers until translated to
machine language.

6
Assembly Language …
 Computer usage increased rapidly with the
arrival of assembly languages, but
programmers still had to use many
instructions to accomplish the simplest tasks.
 For example, the following section of an
assemblylanguage program adds overtime pay to
base pay and stores the result in gross pay:
 load basepay
 add overpay
 store grosspay

7
High Level Language
 To speed up the programming process, high-level
languages were developed in which single
statements could be written to accomplish a
number of tasks.
 High-level languages allow programmers to write
instructions that look almost like everyday
English and contain commonly used
mathematical notations.
 For example a payroll program written in a
highlevel language might contain a statement such
as
8
 grossPay = basePay + overTimePay

High Level Language …


o High level language program is also called source
code.
o Program written in high level languages are
much easier to maintain and modified .
 Translator programs called compilers and
Interpreter convert high-level
language programs into machine
language.

9
 Some examples include BASIC, FORTRAN,
Java, C,C++, Pascal and Microsoft’s .NET

Programming Paradigm
o Paradigm can also be termed as method to solve
some problem or do some task.
o Programming paradigm is an approach to solve
problem using some programming language.
o There are lots for programming language that are
known but all of them need to follow some strategy
when they are implemented and this
methodology/strategy is paradigms.
o The two most known programming paradigms are :
I. Structured programming
10
II. Object oriented programming

Structured programming
o In Structured Programming a programmer who is faced with some
problem must identify a computing task that needs to be performed in order
to solve the problem. o Programming then consists of finding a sequence of
instructions that will accomplish that task. o Structured Programming
focuses on process/ logical structure and the data required for that process.
o Structured Programming is also known as Modular Programming o
In Structured Programming, Programs are divided into small self contained
functions. xdx

11
Structured programming …
 Structured programming follows top-down
approach.
 In Structured programming data was separate from the
code.
 Structured Programming is less secure as there is no
way of data hiding.
 Structured Programming provides less reusability,
more function dependency.
 Less abstraction and less flexibility.

12
 C and Pascal are examples of procedural programming
languages

Programs with Structural


Programming
1. Unrestricted Access o Functions have unrestricted

access to global data.

2. Real-World Modeling

o Unrelated functions and data, the basics of the procedural

paradigm, provide a poor model of the real world.

13
3. Difficult of Creating New Data Types o Traditional

languages are not extensible because they


will not let you create new data types.

Object-Oriented Programming (OOP)


 It is a modern programming paradigm that allows the
Programmer to model a problem in a real-world as an
object.
 Allows us to decompose a problem into a number of
entities called objects and then build data and functions
(methods) around them.
 Hence, programs are divided into what are known as
objects

14
 Binds data more closely to the functions that operate on
it and protects it from unintentional modification by
other functions.
 Hence, Object Oriented Programming is more secure
as having data hiding feature.
 Follows bottom-up approach in program design
Object Oriented Programming…
 An object represents an entity in the real world that can
be distinctly identified.
 Everywhere you look in the real world you see objects -
people, animals, plants, cars, planes, buildings, computers
and so on.
 Humans think in terms of objects. Telephones, houses,
traffic lights and water are just a few more objects.

15
 All objects have attributes (e.g., a car has a size, shape,
color and weight), and they all exhibit behaviors (e.g., a
car accelerates, brakes and turns).
 Humans learn about existing objects by studying their
attributes and observing their behaviors.
 Comparisons can be made, for example, between babies
and adults and between humans and chimpanzees.

Object Oriented Programming…


 OOP models object by their attributes and behaviors
just as we describe real-world objects.
 OOP also takes advantage of class relationships,
where objects of a certain class, such as a class of
vehicles, have the same characteristics (cars, trucks,
16
little red wagons and taxi have much behaviors in
common).
 OOP also models communication between objects.
 Just as people send messages to one another; objects
also communicate via messages.

Object Oriented Programming…


 For example, suppose you want to write a program that
automates the video rental process for a local video store.
 The two main objects in this problem are the video and
the customer.
 Then, specify for each object the relevant data and possible
operations to be performed on that data.

17
 For a video object, the data might include: movie name,
starring actors, producer, production company, number of
copies in stock
 Some of the operations on a video object might include:
 checking the name of the movie.
 reducing the number of copies in stock by one after a copy is
rented.
 incrementing the number of copies in stock by one after a
customer returns a copy.

Object Oriented Programming…


 OOP give emphasis for data rather than procedure
 Data is not allowed to move freely around a system, but it
is tied closely to the functions that operate on it.(i.e. Data
is hidden from external functions)
18
 Data is protected because the data belonging to an object
can only be accessed and modified by the methods of that
object.
 Different objects can 'talk' to each other through their
methods.
 In this way, Object A cannot directly modify data belonging
to Object B – but it can call a method of Object B that in
turn modifies the data.

What is Java
 Java is high level programming language developed by a
team led by James Gosling at Sun Microsystems.
 Originally called Oak, it was designed in 1991 for use
in consumer electronic applications.
19
 In 1995, renamed Java, it was redesigned for
developing Internet applications as well.
 Java is modeled after C and C++, and much of the
syntax and object-oriented structure is borrowed
from C++.
 Java is simple, object oriented, secure, portable and
high performance.

What is Java…
 Java can be used to create two types of programs:
applications and applets.
 Java applications are more general programs written in the
Java language.
 Java applications don’t require a browser to run.(desktop
20
application or stand alone application)
 Applets are Java programs that are downloaded over the
World Wide Web and executed by a Web browser on the
reader’s machine (web based application)
 Java offers two ways of creating dynamic web content:
 Applets-which are Java programs which are run by a client
computer’s web browser
 Servlets-which are Java programs which are run by the web server.

What is Java…
 Java programs are platform independent.
 Java programs are portable - it is possible to move
java programs from one computer system to another.
 Java promise: “Write once, run everywhere”.

21
 Java differs from other programming languages in that
it is both compiled and interpreted language.
 Java is Powerful: massive libraries.

Typical Java Development Environment


 There are five phases in creating and executing a
Java application using a Java development
environment.
 They are:-
 Create/edit
 compile
 load
 verify and
22
 execute

Phase 1: Creating a Program


 It consists of writing a java source code and editing a file with an
editor program or IDE.
 Integrated development environments (IDEs) - provide tools
that support the software development process, including
editors - for writing and editing programs and debuggers - for
locating logic errors.
 Popular IDEs include:-
 Eclipse ([Link]) NetBeans ([Link])
 JBuilder ([Link]) JCreator ([Link])
 BlueJ ([Link])
 jGRASP ([Link]) jEdit ([Link]).
 Then Make any necessary corrections and save the program on
a secondary storage device, such as your hard drive.

23
 A file name ending with the .java extension indicates that
the file contains Java source code.

Phase 2: Compiling a Java Program into


Bytecodes
 Use the command javac to compile a program.
 For example, to compile a program called
[Link], you would type javac
[Link] in the command window of your
system
 If the program compiles, the compiler produces a
.class file called [Link] that contains the
compiled version of the program.

24
 The Java compiler translates Java source code into
bytecodes

Phase 2: Compiling a Java Program into


Bytecodes…
 Bytecodes are a set of instructions that looks like a machine
codes, but it is not specific to any one processor or platform.
 Bytecodes are executed by the Java Virtual Machine
(JVM)—a part of the JDK.
 A virtual machine (VM) is a software application that simulates a
computer, but hides the underlying operating system and
hardware from the programs that interact with the VM.
 Unlike machine language, which is dependent on specific
computer hardware, bytecodes are platform-independent
instructions
25
 So, Java’s bytecodes are portable

Phase 3: Loading a Program into Memory


 In Phase 3, the program must be placed in memory
before execution-which is known as loading.
 Hence the class loader takes the .class files containing
the program’s bytecodes and transfers them to
primary memory.

Phase 4: Bytecode Verification


 In Phase 4, the bytecode verifier examines their
bytecodes to ensure that they are valid and do not
violate Java’s security restrictions.

26
 Java enforces strong security, to make sure that Java
programs arriving over the network do not damage
your files or your system (as computer viruses and
worms might).

Phase 5: Execution
 In Phase 5, the JVM executes the program’s bytecodes.
 The JVM is invoked by the java command.
 For example, to execute a Java application called Welcome, you
would type the command java Welcome in a command window
to invoke the JVM.
 In early Java versions, the JVM was simply an interpreter
for Java bytecodes.
 This caused most Java programs to execute slowly because the
JVM would interpret and execute one bytecode at a time.
27
 Today’s JVMs typically execute bytecodes using a
combination of interpretation and so-called just-
intime (JIT) compilation.

Phase 5: Execution…
 Today’s JVMs analyzes the bytecodes searching for hot
spots— parts of the bytecodes that execute frequently.
 For these parts, a just-in-time (JIT) compiler - known
as the Java HotSpot compiler- translates the bytecodes
into the underlying computer’s machine language.
28
 Thus Java programs actually go through two compilation
phases
 One in which source code is translated into bytecodes
 Second is during execution- the bytecodes are translated into
machine language for the actual computer on which the program
executes.

29
Typical Java Development Environment

30
The Java Language Specification, API and JDK
 Computer languages have strict rules of usage.
 If you do not follow the rules when writing a program,
the computer will be unable to understand it.
 The Java language specification is defines the
syntax and semantics of the Java programming
language.
 The application program interface (API) contains
predefined classes and interfaces for developing Java
programs.
 The Java language specification is stable, but the API is
still expanding.

31
The Java Language Specification, API and JDK
 Java comes in three editions:
1. Java Standard Edition (Java SE) - can be used to
develop client-side standalone applications.
2. Java Enterprise Edition (Java EE) can be used to
develop server-side applications..
3. Java Micro Edition (Java ME) - can be used to develop
applications for mobile devices, such as cell phones.

The Java Language Specification, API and JDK


 There are many versions of Java SE.
 Each version has a Java Development Toolkit (JDK).
 For Java SE 6, the Java Development Toolkit is called JDK
32
1.6 (also known as Java 6 or JDK 6).
 JDK consists of a set of separate programs, each
invoked from a command line, for developing and
testing Java programs.
 Besides JDK, you can use a Java development tool
(e.g., Net- Beans, Eclipse, and Jcreator) - for rapidly
developing Java programs.

33
Basic principles of OOP
Object
 Object is a software bundle that has State and Behavior and it
occupies memory.
 We can also define Object as a set of data items (fields) with
operations (methods ) to manipulate them.
 Example: dogs have states (name, color, hungry, breed) and behaviors
(bark, fetch, and wag tail).
 Object combines data and operations in one place.
 The state of an object (also known as its properties or
attributes) is represented by data fields with their current
values.
 A circle object, for example, has a data field radius, which is the
property that characterizes a circle.
 A rectangle object has data field’s width and height, which are the
properties that characterize a rectangle.

34
Basic principles of OOP
Object…
 The behavior of an object (also known as its actions) is
defined by methods.
 Method is an action performed by an object
 To invoke a method within an object is to ask the object
to perform an action.
 For example, you may define a method named getArea()
for circle objects.
 A circle object may invoke getArea() to return its area.
 objects interact and communicate with each other by
sending messages to each other.

35
Basic principles of OOP… Class
 A class is a template or blueprint that defines what an
object’s data fields and methods will be.
 It defines the states and the behaviors common to all objects
of a certain kind.
 Class is a collection of objects of similar type.
 Classes are user-defined data types & behave like the built-in
types of programming language.
 An object is an instance of a class.
 E.g Ibsa is an instance of a Student
 You can create many instances of a class.
 Creating an instance is referred to as instantiation.

36
 The terms object and instance are often used
interchangeable.

37
Basic principles of OOP…

Class Declaration
 The syntax for a simple class declaration is modifiers class class-
name
{
body
}
 Where the optional modifiers may be one or more of the three
keywords { public, abstract, final }
 Class-name is any valid identifier
 Body is a sequence of declarations of variables, constructors,
and methods
 Modifier Meaning
 Public - It is accessible from all other classes
 Abstract- The class cannot be instantiated
 Final -No subclasses can be declared

38
Basic principles of OOP…
 A class that is declared final cannot be a superclass.

Abstraction
 Also known as information hiding.
 Ignore details when appropriate
 Think about what a method/object/class does, not how it
does it.
 Objects have the property of information hiding.
 This means that objects may know how to communicate with
one another across well-defined interfaces, but normally they are
not allowed to know how other objects is
implementedimplementation details are hidden within the objects
themselves.
 It is one of the fundamental ways to handle complexity.

39
Basic principles of OOP…
 Example driving a car effectively
 E.g. Sort(insertion, selection, bubble)

Encapsulation
 OOD encapsulates (i.e., wraps) attributes and
operations (behaviors) into objects - an object’s
attributes and operations are intimately tied together.
 Is the mechanism that binds together code and the
data object manipulates.
 Put related things in the same place
 I.e. group related data and operations in an object
 Each object has its own data and knows how to use it
40
Basic principles of OOP…
 Hide internal representation/implementation
 Deny external access to internal fields/methods

Inheritance
 Inheritance is a form of software reuse in which, new
classes of objects are derived by absorbing characteristics
of existing classes and adding unique characteristics of
their own.
 Inheritance is the process by which one object acquires
the properties of another object.
 Classical Inheritance: “is-a kind of” relationship.
 In inheritance, an object of a subclass can also be treated as
an object of its superclass.
41
Basic principles of OOP…
 For example, a car is a vehicle.
 Example: fruits and types of fruit (an apple is a type of fruit)
 Goal of inheritance: code reuse

Polymorphism
 The ability to take more than one form.
 The same word or phrase can be mean different things in
different contexts
 One instruction means different things to different agents
 In terms of the OOP, this means that a particular operation
may behave differently for different sub-classes of the same
class.
 Technically: many objects can implement same interface in their
own way.

42
Basic principles of OOP…
 In Java, two or more classes could each have a method called
output
 Each output method would do the right thing for the class that it was
in.
 One output might display a number whereas a different one might
display a name.

43
A Simple Java Program
 Let us begin with a simple Java program that displays the
message “Welcome to Java!” on the console.
 Console refers to text entry and display device of a
computer.
1 public class Welcome {
2 public static void main(String[] args) {
3 // Display message Welcome to Java! to the console
4 [Link]("Welcome to Java
Programming!");
5 }
6 }

44
Description of the program
 Line 1 defines a class.
public class Welcome {
 Every program in Java consists of at least one class definition that is defined by
you - the programmer.
 These classes are known as programmer-defined classes, or user-defined
classes.
 The class keyword introduces a class definition in Java and is immediately
followed by the class name.(In this example, the class name is Welcome.)
 Every class we define begins with the public keyword
 Keywords (or reserved words) are reserved for use by java and are always
spelled with all lowercase letters.
 By convention, class names start with an uppercase letter.
 A pair of braces in a program forms a block that groups the program’s
components.
 In Java, each block begins with an opening brace ({) and ends with a closing
brace (}).

45
 Every class has a class block that groups the data and methods of the class.

Description of the program…


 Line 2 defines the main method.
 In order to run a class, the class must contain a method named main.
public static void main( String args[] )
It is a part of every Java application.
 Java applications begin executing at main.
 The parentheses after main indicate that main is a program building block
called a method.
 Java class definitions normally contain one or more methods.
 For a Java application class, exactly one of those methods must be called main.
otherwise, the java interpreter will not execute the application.
 Methods are able to perform tasks and return information when they
complete their tasks.
 The void keyword indicates that this method will perform a task (displaying a
line of text, in this program), but will not return any information when it
completes its task.

46
 The left brace, {, on line 2 begins the body of the method definition. A
corresponding right brace, }, must end the method definition’s body

Description of the program…


 Line 3 is a comment that documents what the program is and how it is
constructed.
 Comments help programmers to communicate and understand the program.
 They are not programming statements and thus are ignored by the compiler.
 In Java, comments are preceded by two slashes (//) on a line, called a line
comment, or enclosed between /* and */ on one or several lines, called
a block comment.
 When the compiler sees //, it ignores all text after // on the same line.
 When it sees /*, it scans for the next */ and ignores any text between
/* and */.
 Here are examples of comments:
// This application program prints Welcome to Java!
/* This application program prints Welcome to Java! */

47
/* This application program
prints Welcome to Java! */

Description of the program…


 Line number 4
 [Link]( "Welcome to Java Programming!" );
 instructs the computer to perform an action, namely to print the
string of characters contained between the double quotation marks.
 This statement prints a message "Welcome to Java Programming!"
command window from which the Java application executes.
(line 4).
 A string is sometimes called a character string, a message or a string
literal.
 We refer to characters between double quotation marks generically
as strings.
 White-space characters in strings are not ignored by the compiler.

48
 Every statement in Java ends with a semicolon (;), known as the
statement terminator.

Creating, Compiling, and Executing a


Java Program
 When you save your java file, the file name must be the
class name followed by the “.java” file-name extension.
 For our application, the file name is [Link].
 All Java class definitions are stored in files ending with the
file-name extension “.java.”
 To compile the program, we open a command window,
change to the directory where the program is stored and
type
 javac [Link]

49
 If the program contains no syntax errors, the preceding
command creates a new file called [Link]
containing the Java bytecodes that represent our
application.
Creating, Compiling, and Executing a
Java Program
 These bytecodes will be interpreted by the java
interpreter when we tell it to execute the program.
 In the command prompt type java Welcome1
 to launch the java interpreter and indicate that it should
load the “.class” file for class Welcome.
 Note that the “.class” file-name extension is omitted from
the preceding command; otherwise the interpreter will
not execute the program.
50
 The interpreter automatically calls method main.
 Next, the statement on line 4 of main displays “Welcome
to Java Programming!”

Creating, Compiling, and Executing a


Java Program
This section demonstrates how to create, compile, and run
Java programs from a command window.

51
52
End of Chapter One

53

You might also like