Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Chapter- 1 Introduction to Object-Oriented Programming

This document provides an introduction to Object-Oriented Programming (OOP) and its fundamental principles, including concepts like objects, classes, methods, inheritance, encapsulation, and polymorphism. It discusses various programming paradigms, highlighting their characteristics and differences, and emphasizes the advantages of OOP, such as code reuse and abstraction. The document also explains how OOP models real-world entities and organizes programs around objects that interact through message passing.

Uploaded by

lensagetu
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

Chapter- 1 Introduction to Object-Oriented Programming

This document provides an introduction to Object-Oriented Programming (OOP) and its fundamental principles, including concepts like objects, classes, methods, inheritance, encapsulation, and polymorphism. It discusses various programming paradigms, highlighting their characteristics and differences, and emphasizes the advantages of OOP, such as code reuse and abstraction. The document also explains how OOP models real-world entities and organizes programs around objects that interact through message passing.

Uploaded by

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

Introduction to Object-

Oriented Programming

Object Oriented Programming -


1
CoSc2051
Introductions
• A Programming language is a notational
system for describing tasks/computations in a
machine and human readable form.
• Most computer languages are designed to
facilitate certain operations and not others:
– numerical computation, or text
manipulation, or I/O.
• More broadly, a computer language typically
embodies a particular programming
paradigm.

• Which programming language?


Object Oriented Programming -
2
CoSc2051
Introductions
• What is a "programming paradigm"?
– Paradigm: "A philosophical and theoretical framework of a
scientific school or discipline within which theories, laws, and
generalizations and the experiments performed in support of
them are formulated;
– broadly: a philosophical or theoretical framework of any kind“
• Paradigms as “ways of organizing thought”
– Programming paradigm = The basic structuring of thought
underlying the programming activity.
• E.g.. when you think of a programming problem, what are you
thinking of?
– the sequence of actions to perform (first download the file, then display it)
– how to divide the problem-space into sub-tasks (to compute the spanning tree,
i can divide the graph arbitrarily in two, and then …)
– what are the agents involved (sensors, a simulator, a renderer, …)
– what data do we need to handle? do we need intermediate representations?
what are the relations between the different forms?
Object Oriented Programming -
3
CoSc2051
Programming Paradigms :
Programming languages
• Since a task can be solved in different ways
(paradigms), the language used to describe
the solution differs in abstractions, structures
due to the way in which the problem is solved.
• A programming paradigm is a fundamental
style of computer programming.
• Programming paradigms differ in:
– the concepts and abstractions used to represent
the elements of a program (such as objects,
functions, variables, constraints, etc.)
– the steps that compose a computation (assignation,
evaluation, data flow, control flow, etc.).
Object Oriented Programming -
4
CoSc2051
Programming Paradigms :
Programming languages
.
Imperative/ Object
Algorithmic Declarative Oriented

Functional Logic
Programming Programming
Algol Lisp Prolog Smalltalk
Cobol Haskell Simula
PL/1 ML C++ , C#
Ada Miranda Java ,VB
C APL
Modula-3

Object Oriented Programming -


5
CoSc2051
Imperative paradigms
 It is based on commands that update variables in
storage.
 Explicitly tells the computer "how" to accomplish it.
 The Latin word imperare means “to command”.
 E.g GO TO command
 The language provides statements, such as
assignment statements, which explicitly change the
state of the memory of the computer.
 This model closely matches the actual executions of
computer and usually has high execution efficiency.
 Includes procedural & structured programming
 Many people also find the imperative paradigm to
be a more natural way of expressing themselves.
Object Oriented Programming -
6
CoSc2051
Imperative paradigms
 Advantages :
 Efficient;
 Close to the machine;
 Popular;
 Familiar.
 Disadvantages :
 The semantics of a program can be complex to
understand or prove
 debugging is harder;
 Abstraction is more limited than with some
paradigms;
 Order is crucial, which doesn't always suit itself to
problems.
Object Oriented Programming -
7
CoSc2051
Functional programming paradigms
 In this paradigm we express computations as the
evaluation of mathematical functions.
 Functional programming paradigms treat values
as single entities.
 Unlike variables, values are never modified.
 Instead, values are transformed into new values.
 Computations of functional languages are
performed largely through applying functions to
values,.
 It uses functions to perform everything.
 It is a form of declarative programming.
 In this, the command execution order is not
fixed. Object Oriented Programming -
8
CoSc2051
Functional programming paradigms
 Advantages:
 The high level of abstraction, removes the possibility of
committing many classes of errors;
 The lack of dependence on assignment operations, allowing
programs to be evaluated in many different orders.
 This evaluation order independence makes function-oriented
languages good candidates for programming massively parallel
computers;
 The absence of assignment operations makes the function-
oriented programs much more amenable to mathematical
proof and analysis than are imperative programs.
 Disadvantages:
 Perhaps less efficiency
 Problems involving many variables or a lot of sequential
activity that are sometimes easier to handle imperatively or
with object-oriented programming.
Object Oriented Programming -
9
CoSc2051
Logic programming paradigms
 The Logical Paradigm takes a declarative
approach to problem-solving.
 Various logical assertions about a situation are
made, establishing all known facts.
 Then queries are made.
 The role of the computer becomes
maintaining data and logical deduction.
 Logical Paradigm Programming:
 A logical program is divided into three sections:
1. a series of definitions/declarations that define the problem
domain
2. statements of relevant facts
3. statement of goals in the form of a query
Object Oriented Programming -
10
CoSc2051
Logic programming paradigms
 While the functional paradigm emphasizes the
idea of a mathematical function, the logic
paradigm focuses on predicate logic, in which
the basic concept is a relation.
 Logic languages are useful for expressing
problems where it is not obvious what the
functions should be.
 For example consider the uncle relationship:
 a given person can have many uncles, and another
person can be uncle to many nieces and nephews.
 Let us consider now how we can define the
brother relation in terms of simpler relations and
properties father, mother, and male.
 Using the Prolog logic language
Object Oriented one can
Programming - say:
11
CoSc2051
Logic programming paradigms
clauses
brother(X,Y) :- /* X is the brother of Y */
/* if there are two people F and M for which*/

father(F,X), /* F is the father of X */


father(F,Y), /* and F is the father of Y */
mother(M,X), /* and M is the mother of X */
mother(M,Y), /* and M is the mother of Y */
male(X). /* and X is male */
 Predicates
 mother(sara, jack). /* sara is the mother of jack */ is
fact.
 Query
? mother(sara, jack).
Yes
Object Oriented Programming -
12
CoSc2051
Logic programming paradigms
 Advantages:
 system solves the problem, so the programming
steps themselves are kept to a minimum;
 Proving the validity of a given program is simple.

Object Oriented Programming -


13
CoSc2051
The Object-Oriented Paradigm
 Object Oriented Programming (OOP) is a paradigm
in which real-world objects are each viewed as
separate entities having their own state which is
modified only by built in procedures, called
methods.
 Alan Kay characterized the fundamental of OOP as
follows:
– Everything is modeled as object
– Computation is performed by message passing:
• objects communicate with one another via message passing.
– Every object is an instance of a class where a class
represents a grouping of similar objects.
– Objects are organized into classes, from which they
inherit methods and equivalent variables.
Object Oriented Programming -
14
CoSc2051
The Object-Oriented Paradigm
 Inheritance: defines the relationships between classes.
 Inheritance gives OOP its chief benefit over other
programming paradigms - relatively easy code reuse
and extension without the need to change existing
source code.
 The Object Oriented paradigm focuses on the objects
that a program is representing, and on allowing them
to exhibit "behavior".
 Unlike imperative paradigm, where data are passive
and
procedures are active, in the O-O paradigm data is
combined with procedures to give objects, which are
thereby rendered active.

Object Oriented Programming -


15
CoSc2051
Fundamental Principles of OOP

1. Objects
2. Classes
3. Methods and Messages
4. Abstraction
5. Inheritance
6. Encapsulation
7. Polymorphism

Object Oriented Programming -


16
CoSc2051
OOP Concepts
 In object-oriented programming (OOP), programs are
organized into objects
 The properties of objects are determined by their class
 Objects act on each other by passing messages.

 Object
 Definition:
An object is a software bundle that has State and
Behavior.
 Software Objects are often used to model real-world
objects.
 Example:
dogs have states (name, color, hungry, breed) and
behaviors (bark, fetch, and wag tail).
Object Oriented Programming -
17
CoSc2051
Object Examples
 Example 1: Dogs
 States: name, color, breed, and “is hungry?”
 Behaviors: bark, run, and wag tail
 Example 2: Cars
 States: color, model, speed, direction
 Behaviors: accelerate, turn, change gears

Object Oriented Programming -


18
CoSc2051
Class
 Definition: A class is a blueprint that defines
the states and the behaviors common to all
objects of a certain kind.
 In the real world, you often have many objects
of the same kind.
 For example, a guard dog, herding dog, snoop
dog . . .
 Even though all dogs have four legs, and bark,
each dog’s behavior is independent of other
class Dog {
dogs.
 For example: // state and behavior
 Dog #1 is a black Poodle,}
 Dog #2 is a redObject
Irish Setter
Oriented Programming -
CoSc2051
19
Methods
 An Object's behavior is defined by its
methods
 Methods, like fields, are written inside the
braces of the class
 Methods can access the fields (the state) of
their object and can change them
class Dog {

String name; // field

public void bark() { // behavior


...
}
}
Object Oriented Programming -
20
CoSc2051
Message
 Definition: Software objects interact and
communicate with each other by sending
messages to each other.

 Example: when you want your dog to gather a


herd of goats, you whistle and send him out.

Object Oriented Programming -


21
CoSc2051
Inheritance
 Inheritance is a mechanism in which one
object acquires all the states and behaviors of
a parent object.
 Inheritance allows child classes inherits the
characteristics of existing parent class
 Attributes (fields and properties)
 Operations (methods)
 Child class can extend the parent class
 Add new fields and methods
 Redefine methods (modify existing behavior)
 A class can implement an interface by
providing implementation for all its methods.
 Inheritance is same asCoSc2051
specialization.
Object Oriented Programming -
22
Inheritance
 Inheritance terminology

base class /
derived class inherits parent class

class implements interface

derived interface implements base interface

E.g. A old style television (idiot box) is


transformed with extra features into slim and
smart television where it re-used the properties of
Object Oriented Programming -
old television. CoSc2051
23
Inheritance – Benefits
 Inheritance has a lot of benefits
– Extensibility
– Reusability
– Provides abstraction
– Eliminates redundant code
 Use inheritance for building is-a relationships
– E.g. dog is-a animal (dogs are kind of animals)
 Don't use it to build has-a relationship
– E.g. dog has-a name (dog is not kind of name)

Object Oriented Programming -


24
CoSc2051
Inheritance – Example
. Base class
Person
+Name: String
+Address: String

Derived class Derived class

Employee Student
+Company: String +School: String
+Salary: double

Object Oriented Programming -


25
CoSc2051
Encapsulation
 Encapsulation is a process of wrapping code
and data together into a single unit.
 Encapsulation is the process of grouping data
in a single section.
 Encapsulation hides the implementation
details
 Class announces some operations (methods)
available for its clients – its public interface.
 All data members (fields) of a class should be
hidden.
 Accessed via properties (read-only and read-
write).
Object Oriented Programming -
 No interface members should be hidden
CoSc2051
26
Encapsulation – Example
 Example: Complete television is single box
where all the mechanism are hidden inside
the box all are capsuled.
 Data fields are private.
 Constructors and accessors are defined
(getters and setters)
Person
-name : string
-age : TimeSpan

+Person(string name, int


age)
+Name : string { get;
set; } Object Oriented Programming - 27
CoSc2051
Encapsulation – Benefits
 Ensures that structural changes remain local:
 Changing the class internals does not affect any
code outside of the class
 Changing methods' implementation does not reflect
the clients using them
 Encapsulation allows adding some logic when
accessing client's data
 E.g. validation on modifying a property value
 Hiding implementation details reduces
complexity -> easier maintenance.
 We can make a class read-only or write-
only:
 for a read-only –Object
a getter method and write-only - a
Oriented Programming -
28
setter method will be used. CoSc2051
Polymorphism
 Polymorphism is a concept in which we can
execute a single operation in different ways.
 Polymorphism is same as generalization.
 Polymorphism = ability to take more than one
form (objects have more than one type)
 A class can be used through its parent interface
 A child class may override some of the behaviors of
the parent class
 Polymorphism allows abstract operations to
be defined and used.
 Abstract operations are defined in the base class'
interface and implemented in the child classes
 Declared as abstract or virtual
Object Oriented Programming -
29
CoSc2051
Polymorphism
 Why handle an object of given type as object
of its base type?
– To invoke abstract operations
– To mix different related types in the same
collection
 E.g. List<object> can hold anything
– To pass more specific object to a method that
expects a parameter of a more generic type
– To declare a more generic field which will be
initialized and "specialized" later

Object Oriented Programming -


30
CoSc2051
Polymorphism
Abstra
. class
ct
Figure Abstract
action
+CalcSurface() : double

Concrete
class Square Circle
-x : int -x : int
-y : int -y : int
Overriden -size : int -radius: int Overriden
action action

override CalcSurface() override CalcSurface()


{ {
return size * size; return PI * radius * raduis;
} }
Object Oriented Programming -
31
CoSc2051
Abstraction
 Abstraction is a process of hiding the
implementation details and showing only
functionality to the user.
 Abstraction means hiding internal details and
showing the required things.
– E.g.: pressing the accelerator will increase the
speed of a car.
– But the driver doesn’t know how pressing the
accelerator increases the speed – they don't
have to know that.
 Technically abstract means something
incomplete or to be completed later.
 In Java, we can Object
achieveOriented abstraction
Programming - in two 32
CoSc2051
Overview of Java Programming
 Java is an object-oriented programming
language
 The Java programming language was created
by Sun Microsystems, Inc.
 It was introduced in 1995 and it's popularity
has grown quickly since
 Its primary feature is that it could function
nicely in a networked environment.
 The explosion of WWW created an
environment in which the language could live.

Object Oriented Programming -


33
CoSc2051
Overview of Java Programming
 Java technology can be seen as both a
language and a platform.
 Using it you can write applications that can
run on practically any device, including a PC,
PDA, a cellular phone or a television.
 The Java platform is formed from two
components:
– The Java application programming interface
(Java API)
 Set if libraries that are used to accomplish tasks such as
creating GUIs, performing file I/O and establishing network
comm.
– The Java Virtual Machine (JVM)
 Is in charge of executing your
Object Oriented code in a- specific
Programming
34
CoSc2051
environment.
Characteristics of Java
 Java Is Simple
 Java Is Object-Oriented
 Java Is Distributed
 Java Is Interpreted
 Java Is Robust
 Java Is Secure
 Java Is Architecture-Neutral
 Java Is Portable
 Java's Performance
 Java Is Multithreaded
 Java Is Dynamic
Object Oriented Programming -
35
CoSc2051
Java Program Structure
 In the Java programming language:
– A program is made up of one or more classes
– A class contains one or more methods
– A method contains program statements
 These terms will be explored in detail
throughout the course
 A Java application always contains a method
called main

Object Oriented Programming -


36
CoSc2051
Java Program Structure
.// comments about the class

public class MyProgram


{

// comments about the method

public static void main (String[] args)


{
method body method header

Object Oriented Programming -


37
CoSc2051
Development Environments
 There are many tools to do java programming, to
the very least you need to have
 Sun Java Development Kit (JDK/ Recent version JDK 8)
 Text editor such as Microsoft Notepad
 Integrated Development Environment IDE for Java
 NetBeans (from Sun/Oracle)
 Eclipse (from IBM)
 Borland JBuilder
 BlueJ
 JCreator
 DrJ
 IntelliJ
 Android Studio and
 Many others
Object Oriented Programming -
38
CoSc2051
The Compiler and the Java Virtual
Machine
 A programmer writes Java programming
statements for a program called source code
 A text editor is used to edit and save a Java source
code file.
 Source code files have a .java file extension.
 A compiler is a program that translates source
code into an executable form.
 A compiler is run using a source code file as input.
 Syntax errors caught during compilation if exist.
 Syntax errors are mistakes that violate the rules of
the programming language.
 Compiler creates another file that holds the
translated instructions and it is called byte code.
Object Oriented Programming -
39
CoSc2051
The Compiler and the Java Virtual
Machine
 A program written in a high-level language like
java is called a source program.
 Since a computer cannot understand a source
program. Program called a compiler is used to
translate the source program into a machine
language program called an object program.
 The object program is often then linked with
other supporting library code before the object
can be executed on the machine.

Source File Compiler Object File Linker Excutable File

Object Oriented Programming -


40
CoSc2051
The Compiler and the Java Virtual
Machine
 Most compilers translate source code into
executable files containing machine code.
 The Java compiler translates a Java source file
into a file that contains byte code instructions.
 Byte code files end with the .class file extension.
 Byte code instructions are the machine
language of the Java Virtual Machine (JVM) and
cannot be directly executed by the CPU.
 The JVM is a program that emulates a micro-
processor.
 The JVM executes instructions as they are read.
 JVM is often called an interpreter.
 Therefore, Java is both
Object compiled
Oriented Programming - and
41
CoSc2051
Compiling Java Source Code
 With Java, you write the program once, and
compile the source program into a special
type of object code, known as bytecode.
 The bytecode can then run on any computer
with a Java Virtual Machine, as shown below.
 Java Virtual Machine is a software that
interprets Java bytecode.
Java Bytecode

Java Virtual
Machine

Any
Computer

Object Oriented Programming -


42
CoSc2051
Program Development Process
.
Saves Java statements Source code
Text editor
(.java)
r e a d by
Is
Produces Byte code
Java compiler (.class)
t e d by
e rp re
Is int
Java Results in Program
Virtual Execution
Machine

Object Oriented Programming -


43
CoSc2051
Multiple Compilers
 Because different operating systems
(Windows, Macs, Unix) require different
machine code, you must compile most
programming languages separately for each
platform. Unix
compiler
program

compiler MAC

compiler
Win

Object Oriented Programming -


44
CoSc2051
Your First Java Program
 Open your text-editor and type the following
piece of Java code exactly:
class HelloWorld {
public static void main(String[]
args) {

System.out.println("Hello World!");

}
}
 Save this file as HelloWorld.java (watch
capitalization) in the following directory:
c:\java

Object Oriented Programming -


45
CoSc2051
Compiling and Running Your First
Program
 Open the command prompt in Windows
 To run the program that you just wrote, type at the
command prompt: cd c:\java
 Your command prompt should now look like this: c:\
java>
 To compile the program that you wrote, you need to
run the Java Development Tool Kit Compiler as follows:
At the command prompt type: c:\java> javac
HelloWorld.java
 You have now created your first compiled Java program
named HelloWorld.class
 To run your first program, type the following at the
command prompt: c:\java>java HelloWorld
Although the file name includes the .class
extension , this part
Objectof the name
Oriented must
Programming - be left off 46
CoSc2051
when running the program with the Java interpreter.
Creating, Compiling, and Running
Programs
.
Create/Modify Source Code

Source code (developed by the programmer)


Saved on the disk
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!"); Source Code
}
}

Compile Source Code


Byte code (generated by the compiler for JVM i.e., javac Welcome.java
to read and interpret, not for you to understand)

Method Welcome() If compilation errors
0 aload_0 stored on the disk

Bytecode
Method void main(java.lang.String[])
0 getstatic #2 …
3 ldc #3 <String "Welcome to
Java!">
5 invokevirtual #4 …
8 return Run Byteode
i.e., java Welcome

Result

If runtime errors or incorrect result

Object Oriented Programming -


47
CoSc2051
Types of Java Program
 Types All Java programs can be classified as
Applications and Applets.
 Java applications are large programs that
run stand-alone, with the support of a virtual
machine.
 Applet is a relatively small Java program
executed under the by a browser (inside an
appletviewer).
 Applets are great for creating dynamic and
interactive web applications of Java Program.
 Advantages of Applets

Object Oriented Programming -


48
CoSc2051
Types of Java Program
 Advantages of Applets :
 Execution of applets is easy in a Web browser
and does not require any installation or
deployment procedure in realtime programming
(where as servlets require).
 Writing and displaying (just opening in a
browser) graphics and animations is easier than
applications.
 In GUI development, constructor, size of frame,
window closing code etc. are not required (but
are required in applications).

Object Oriented Programming -


49
CoSc2051
Types of Java Program
.

Object Oriented Programming -


50
CoSc2051
Bye
Take a look :
https://docs.oracle.com/en/java/

Object Oriented Programming -


51
CoSc2051

You might also like