Introduction to Object-
Oriented Programming
OOP - CoSc2051 1
Introductions
• Chapter 1: Introduction to OOP
– Types of programming paradigms
– Overview of OO principles
– Editing, Compiling and Interpreting
OOP - CoSc2051 2
Introductions
All computer programs consist of two elements: code and data.
A Programming language is a notational system for describing
tasks/computations in a machine and human readable form.
Computer languages are designed to facilitate certain operations.
Computer language typically embodies a particular
programming paradigm.
Which programming language?
OOP - CoSc2051 3
Introductions
• What is a "programming paradigm"?
• Paradigms is “ a ways of organizing thought”
– Programming paradigm = The basic structuring of thought underlying the
programming activity.
a method to solve some problem or do some task.
• 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
– 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?
OOP - CoSc2051 4
Programming Paradigms
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.).
OOP - CoSc2051 5
Programming Paradigms
OOP - CoSc2051 6
Programming Paradigms
.
Imperative/
Algorithmic Declarative
Procedural Object Functional Logic Database
programming Oriented Programming Programming Programming
Algol Smalltalk Lisp Prolog SQL
Cobol Simula Haskell
PL/1 C++ , C# ML
Ada Java ,VB Miranda
C APL
Modula-3
Fortan
Basic
OOP - CoSc2051 7
Imperative paradigms
It is based on commands that update variables in storage.
The main : Explicitly tells the computer "how" to accomplish it.
The Latin word imperare means “to command”.
E.g GO TO command
It works by changing the program state through assignment statements.
It performs step by step task by changing state.
The paradigm consist of several statements and after execution of all,
the result is stored.
Includes procedural & structured programming.
Many people also find the imperative paradigm to be a more natural
way of expressing themselves.
OOP - CoSc2051 8
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.
Parallel programming is not possible
OOP - CoSc2051 9
Declarative Programming
Declarative programming is the opposite of imperative programming
in the sense that the programmer doesn't give instructions about
how the computer should execute a task, but rather on what result
is needed.
Declarative languages aim to bring programming languages closer to
human language and thinking.
It often considers programs as theories of some logic.
It may simplify writing parallel programs.
The focus is on what needs to be done rather how it should be
done basically emphasize on what code is actually doing.
It just declares the result we want rather how it has be produced.
OOP - CoSc2051 10
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.
OOP - CoSc2051 11
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 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.
OOP - CoSc2051 12
Logic programming paradigms
The LP 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
OOP - CoSc2051 13
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 one can say:
OOP - CoSc2051 14
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
OOP - CoSc2051 15
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.
OOP - CoSc2051 16
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.
In OOP:
– 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.
OOP - CoSc2051 17
Fundamental Principles of OOP
1. Objects
2. Classes
3. Methods and Messages
4. Abstraction
5. Encapsulation
6. Inheritance
7. Polymorphism
OOP - CoSc2051 18
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.
What is 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).
OOP - CoSc2051 19
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 dogs.
For example:
class Dog {
Dog #1 is a black Poodle,
// state and behavior
Dog #2 is a red Irish Setter
}
OOP - CoSc2051 20
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
// behavior
public void bark()
{
...
}
}
OOP - CoSc2051 21
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.
OOP - CoSc2051 22
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)
Inheritance is a specialization.
OOP - CoSc2051 23
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 old television.
OOP - CoSc2051 24
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)
OOP - CoSc2051 25
Inheritance – Example
Base class
. Person
+Name: String
+Address: String
Derived class Derived class
Employee Student
+Company: String +School: String
+Salary: double
OOP - CoSc2051 26
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).
No interface members should be hidden.
OOP - CoSc2051 27
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; }
+Age : TimeSpan { get; set; }
OOP - CoSc2051 28
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 reflected to 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 a getter method and
For write-only a setter method will be used.
OOP - CoSc2051 29
Polymorphism
Polymorphism is a concept in which we can execute a single operation
in different ways.
Polymorphism is a 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
OOP - CoSc2051 30
Polymorphism
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;
} }
OOP - CoSc2051 31
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.
In Java, we can achieve abstraction in two ways:
– abstract class and interface.
OOP - CoSc2051 32
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.
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.
OOP - CoSc2051 33
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 of libraries that are used to accomplish tasks such as
creating GUIs, performing file I/O and establishing network
communication.
– The Java Virtual Machine (JVM)
It is executing java code in a specific environment.
OOP - CoSc2051 34
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
OOP - CoSc2051 35
Java Program Structure
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
OOP - CoSc2051 36
Java Program Structure
// comments about the class
.
public class MyProgram
{
Class name
// comments about the method
public static void main (String[] args)
{
method body method header
OOP - CoSc2051 37
Development Environments
There are many tools to write java program, to the very least you
need to have:
Java Development Kit (JDK 8/ Recent version)
Text editor such as Microsoft Notepad
Integrated Development Environment IDE for Java
NetBeans (from Sun/Oracle)
Eclipse (from IBM) IntelliJ
Borland JBuilder Android Studio and
BlueJ Many others
JCreator
DrJ
OOP - CoSc2051 38
The Compiler and the Java Virtual Machine
A programmer writes Java 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 run a source code file by using as input.
Syntax errors caught during compilation if exist.
Syntax errors are mistakes that violate the rules of the programming language.
Compiler produces another file called byte code.
Java byte code interpreted by java virtual machine
OOP - CoSc2051 39
The Compiler and the Java Virtual Machine
A program written in a high-level language like java is called a source
program.
Computer cannot understand a source program.
Program called a compiler is used to translate the source program
into a byte code 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.
OOP - CoSc2051 40
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 cannot be directly executed by the CPU.
The JVM is a program that emulates a micro-processor.
The JVM used to execute byte code.
JVM is often called an interpreter.
Therefore, Java is both compiled and interpreted language.
OOP - CoSc2051 41
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 operating 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
OOP - CoSc2051 42
Program Development Process
Saves Java statements Source code
. Text editor
(.java)
Produces Byte code
Java compiler (.class)
Java Results in Program
Virtual Execution
Machine
OOP - CoSc2051 43
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
OOP - CoSc2051 44
Java Interpreter
• Java is a little different.
• Java compiler produces bytecode not machine code.
• Bytecode can be run on any computer with the Java
interpreter installed.
45
AU/Computer Sc. Dept/Java
Your First Java Program
Open your text-editor and type the following piece of Java code:
class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
Save this file as HelloWorld.java in the following directory:
c:\java
OOP - CoSc2051 46
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 of the name
must be left off when running the program with the Java interpreter.
OOP - CoSc2051 47
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
OOP - CoSc2051 48
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.
OOP - CoSc2051 49
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 real-time
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).
OOP - CoSc2051 50
Types of Java Program
OOP - CoSc2051 51
End of Chapter 1
Next: Objects and Classes
https://docs.oracle.com/en/java
OOP - CoSc2051 52