OOP Chap 1 Deber Markose
OOP Chap 1 Deber Markose
Burie Campus
Department of software engineering
Lecture 1:
Introduction to Object-Oriented Programming
Ayisheshim Almaw
[email protected]
1
Chapter 1 :
INTRODUCTION to OOP
• programming paradigms
• Types of programming paradigms
• Overview of OO principles
• Characteristics/ Features of Java
• The Java language Specifications, API, JDK and IDE
• Creating , Compiling and Executing a Java program.
2
Basic Terminology
5
Imperative programming paradigm
• When you go shopping, you usually write down the name of the
things you need to buy before reaching the mall.
• Similarly, this paradigm consists of a list of programming statements.
• They are first executed, and then the results are stored in a variable. It
is more of a line-by-line instruction given to the computer.
• The imperative programming paradigm is the oldest paradigm and follows the
most basic idea of programming.
• The programs in these paradigms are executed step by step by changing the
current state of the program.
• This type of paradigm takes the order of the steps into consideration
because different arrangements can produce different results.
• Imperative programming mainly focuses on how a program operates.
• Examples of imperative programming are Object oriented
programming, procedural programming, etc.
6
• You may be thinking what style or approach are we talking about.
• Object oriented programming is the approach creation of objects
and creating programs.
• Functional programming: solving problems with series of
functions
• Logic programming: uses sentences in logical form and creates
an expression by using symbols.
• If a programming language support or falls under a certain
paradigm then this means it has some unique feature or it follows
a certain approach that makes it best to solve a certain kind of
problem.
• For example:
• Object-oriented programming is best suited for implementing real-
world entities by hiding important data and finding methods with
the entities. Example C++, Java, Python, etc.
• Logical programming is best for creating logic by a complex 7
• A good programming language should support multiple paradigms
because different programming problems require a different way
to approach.
• If a programing language support only one or two paradigms then
it may not be sufficient or contains feature required.
8
ASSIGNMENT 1
Q1. DEFINE and describe types of programming
paradigms
(Procedural, Object-Oriented, Functional and Logical)
9
Object-Oriented Paradigm
Object-Oriented Programming is a methodology or paradigm to design a
program using classes and objects.
• OOPS is a programming approach which provides solution to real life problems
with the help of algorithms based on real world.
• It uses real world approach to solve a problem. So object oriented technique offers
better and easy way to write program then procedural programming languages
• Communication with an object is done by message passing.
• Objects are organized into classes, from which they inherit methods and
equivalent variables.
• The object-oriented paradigm provides key benefits of reusable code and code
extensibility.
10
Why an object-orientation
• Code recycle and reuse.
• Wrapping up of data into a single unit.
• Easy to partition the work in a project based on objects.
• Message passing technique between objects for communication
makes interface description with external systems much more
straightforward.
• Software Complexity can be easily handled and managed.
• Possible to map objects in a problem domain within a program.
• Data hiding is possible.
• Use of inheritance can eliminate redundant codes in a program11
Overview of OO principles
12
object :
• Any entity that has state and behavior is known as an object.
• An object has three characteristics:
• state: represents data (value) of an object.
• behavior: represents the behavior (functionality) of an object such as
deposit, withdraw etc.
• identity: Object identity is typically implemented via a unique ID.
• Example, a chair, pen, table, keyboard, bike, etc.
• It can be physical or logical.
• Example: A dog is an object because it has states like color, name, breed,
etc. as well as behaviors like wagging the tail, barking, eating, etc.
13
• A class is a group of objects that has common properties.
• class is a template or blueprint from which objects are
created.
14
In the figure below boy ( boy ) Girl ( girl ) by class
( class ) , And the specific person is this kind of Object
( object ):
15
Inheritance
• Inheritance in java is a mechanism in which one object
acquires all the properties and behaviours of parent
object.
• It provides code reusability.
16
Encapsulation
17
Abstraction
• Abstraction refers to hiding the details and showing the essential
things to the user.
• If you look at the image below, whenever we get a call, we get an
option to either pick it up or just reject it. But in reality, there is a
lot of code that runs in the background.
• So you don’t know the internal processing of how a call is
generated, that’s the beauty of abstraction.
18
Polymorphism
19
History of Java
20
Q. Why Oak name for java language?
• Why Oak? Oak is a symbol of strength and choosen as a national
tree of many countries like U.S.A., France, Germany, Romania
etc.
• In 1995, Oak was renamed as "Java" because it was already a
trademark by Oak Technologies.
Q. Why they choosed java name for java language?
The team gathered to choose a new name. The suggested words
were "dynamic", "revolutionary", "Silk", "jolt", "DNA" etc.
They wanted something that reflected the essence of the
technology: revolutionary, dynamic, lively, cool, unique, and easy
to spell and fun to say.
According to James Gosling "Java was one of the top choices along
with Silk". Since java was so unique, most of the team members
preferred java.
21
• Java is an island of Indonesia where first coffee was produced
(called java coffee).
• Notice that Java is just a name not an acronym
• Java is an object-oriented programming language developed by Sun
Microsystems, and it was released in 1995.
• James Gosling initially developed Java in Sun
Microsystems (which was later merged with Oracle Corporation)
What is java?
• Java is a general purpose, concurrent, class based, object
oriented programming language.
• Java as an object-oriented language was designed from the
outset to be platform independent, robust, and secure.
• Platform: Any hardware or software environment in which a
program runs, is known as a platform. Since Java has its own
runtime environment (JRE) and API, it is called platform. 22
Characteristics/ Features of Java
• Object-Oriented - Java supports the features of object-oriented
programming. Its object model is simple and easy to expand.
• Platform independent - Java works on different platforms
(Windows, Mac, Linux, Raspberry Pi, etc.)
• Simple - Java has included many features of C / C ++, which makes
it easy to understand.
• Secure - Java provides a wide range of protection from viruses and
malicious programs.
• Portable - Java provides us with the concept of portability. Running
the same program with Java on different platforms is possible.
• Robust - During the development of the program, it helps us to find
possible mistakes as soon as possible.
• Multi-threaded - The multithreading programming feature in Java
allows you to write a program that performs several different tasks
simultaneously 23
Where java is used?
• According to Sun, 3 billion devices run java. There are many devices where java is
currently used.
• Types of Java Applications
• There are mainly 4 type of applications that can be created using java programming:
1. Standalone Application (desktop application or window-based application): An
application that we need to install on every machine such as media player, antivirus etc.
Example: such as acrobat reader, media player, antivirus etc.
2) Web Application
• An application that runs on the server side and creates dynamic page, is called web
application. Currently, servlet, jsp, struts, jsf etc.
• Example: javatpoint.com,dmu.edu.et etc
3) Enterprise Application
• An application that is distributed in nature, such as banking applications etc. It has the
advantage of high level security, load balancing and clustering. In java, EJB is used for
creating enterprise applications.
• Example: banking applications
4) Mobile Application: An application that is created for mobile devices. Currently Android
and Java ME are used for creating mobile applications.
• Example: Smart Card, Robotics, Games etc. 24
The Java language Specifications, API, JDK
and IDE
• Java language Specifications: a technical specifications of the language
that includes the syntax and semantics of the language.
• API (Application Program Interface): Contains predefined classes and
interfaces for developing java programs.
Three editions of java API
– J2SE: Java 2 Standard Edition
– J2EE: Java 2 Enterprise Edition
– J2ME: Java 2 Micro Edition
Three major java development tools
– Jbulider
– NetBeans
– Eclipse
25
Java JVM, JDK and JRE
26
Java Runtime Environment (JRE)
• JRE : provides the libraries, the Java Virtual Machine, and
other components to run applets and applications written in
the Java programming language.
• JRE does not contain tools and utilities such as compilers or
debuggers for developing applets and applications.
27
JDK (Java Development Kit)
• JDK Includes a complete JRE (Java Runtime Environment) plus
tools for developing, debugging, and monitoring Java applications.
• JDK is required to build and run Java applications and applets.
28
Creating , Compiling and Executing a Java
program. Create/Modify source code
Source Code
Bytecode
Run Bytecode
e.g.java Welcome
Result
29
Phases of a Java Program
Java programs normally go through five phases-
edit, compile, load, verify and execute.
30
Phases of a Java Program
31
Phase 1: Creating a program
• Involves editing a file with an editor
• The following are some Java Integrated Development
Environments (IDEs).
– Jbuilder, NetBeans , Sun ONE Studio, Eclipse, jEdit,
Jcreator, BlueJ, jGRASP, etc.
– Most of this editors can be downloaded for free.
– Any text editor can also be used for creating Java programs.
32
– Java source code file names end with .java extension
Phase 2: Compiling Java Programs into Bytecodes
• 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.
• 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 (platform) with a Java
Virtual Machine
• A virtual machine is a software application that simulates a
computer-JVM is one of the most widely used virtual machine
• Java Virtual Machine, which is part of JRE, is a software that
interprets Java bytecode. Java Bytecode
Macintosh
Running JVM
34
Phase 3: Loading a program
• A program must be placed in memory before it can execute
: a process known as loading.
• The class loader also loads any of the .class files provided
by java that your program uses.
38
Remarks
• Every java program must have at least one class
• In order to run a class, the class must contain a method named main
39
Anatomy of a Java Program
• A java program contains:
– Comments
– Reserved words
– Package
– Modifiers
– Statements
– Blocks
– Classes
– Methods
– The main method
40
Comments
• Preceded by two slashes (//) in a line, or enclosed between /* and */ in one or
multiple lines.
Reserved Words
• Reserved words or keywords are words that have a specific meaning to the compiler
and cannot be used for other purposes in the program.
Example,
class, public, static, and void.
• Packages: A group of predefined classes
Example
• JOptionPane is in javax.swing package i.e it is imported to a program using import
statement.
• java. lang package is imported implicitly in every java program, eg. System class is not
imported b/c it is in this package
Modifiers
• Reserved words that specify the properties of the data, methods, and classes and how they
can be used.
• Ex. public and static, private, final, abstract, and protected.
41
Statements
• Represents an action or a sequence of actions.
• Eg.: System.out.println("Welcome to Java!") is a statement to display the greeting "Welcome to Java!"
• Should end with a semicolon (;).
Block
• A pair of braces in a program forms a block that groups components of a program.
44
Character and String Data Type
Character data type:
– Used to represent a single character
– A character literal is enclosed in single quotation
marks.
Eg. char letter=‘A’;
String Data type
– Represent a string of character
– A predefined class in java library
– It is known as reference type
Eg. Sting message =“Welcome to Java”
45
Variables
• variable is a name which is used to store a value of any type during
program execution.
• A variable is the name of a reserved area allocated in memory. In other
words, it is a name of the memory location.
• It is a combination of "vary + able" which means its value can be
changed. A variable is assigned with a data type.
• An identifier is a name that uniquely identifies a variable, a method
(function), a class or any other element in java that requires a name.
• The following are considered valid in identifiers names:
– Upper case and lower case letters a through z. E.g. int x, string
name…
– Underscore character (_). E.g. string Stud_name…
– The dollar sign ($). E.g. char val$...
– Except for the first character, the digits 0-9. E.g. int x1, x2,.. int 1x,
2x (Wrong)
– Identifiers are case sensitive. E.g. String Name is not the same as
String name 46
Declaration of variable in Java
• Declaring a variable means what kind of data it will
store.
• Variables display named storage locations, whose
values can be changed during the execution of the
program.
• The syntax for declaring a variable is
datatype variableName;
Eg:
int count;
double radius;
double interestRate;
47
Initialization of Variables in Java
• This means assigning a value to variables.
The syntax for initializing a variable is
datatype variableName= value
• // actual initialization
width = 10;
age = 26;
48
Constants Variables
• Represents permanent data that never changes.
double[] myList;
51
Initialize an Array in Java
• By using new operator array can be initialized.
• Example:
int[] age = new int[5]; //5 is the size of array.
Arrays can be initialized at declaration time also.
• Example:
int age[5]={22,25,30,32,35};
String[] cars;
We have now declared a variable that holds an array of strings.
To insert values to it, we can use an array literal - place the values in
a comma-separated list, inside curly braces:
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
To create an array of integers, you could write:
int[] myNum = {10, 20, 30, 40}; 52
Access the Elements of an Array
• You access an array element by referring to the index
number.
• This statement accesses the value of the first element in
cars:
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars[0]); // Outputs Volvo
Change an Array Element
• To change the value of a specific element, refer to the
index number:
• ArrayName[index No]=“value”;
cars[0] = "Opel";
53
54
Two-Dimensional Array Basics
• Used to represent a matrix or a table
int[][] matrix;
55
int jimmy [3][5];
jimmy[1][3] means
56
Control Structures
• Control structures are a way to alter the natural sequence of execution
in a Java program.
• They act as “direction signals” to control the path a program takes.
• The process of performing one statement after another is called the flow
of execution or flow of control.
• Control structures include:
» Block statements
» Decision statements
» Loops
57
Decision Statements
• The control statements that allow alternative actions based up on
conditions that are evaluated at run time are generally called
decision or selection statements.
• These include if and switch statements.
If Statements
• A simple if statement executes an action if and only if the condition
is true.
• The syntax:
if (boolean-expression)
{
statement(s);
} 58
public class Sample{
if(b>a)
System.out.println("b is
greater");
}
}
59
If … Else Statement
• To take alternative actions when the condition is false, you can use a n
if… else statement.
• The actions that a if…else statement specifies differ based on whether
the condition is true or false.
• The syntax:
if (boolean-expression)
{
statement(s)-for-the-true-case;
}
else {
statement(s)-for-the-false-case;
} 60
public class Sample {
if (b > a) {
System.out.println("b is greater");
} else {
System.out.println("a is greater");
} }}
61
Nested if Statements
• The nested if statement can be used to implement multiple
alternatives.
64
Decision Statements
• Sometimes it is necessary for the program to execute the statement several times, and
Java loops execute a block of commands a specified number of times until a condition is
met.
• A computer is the most suitable machine to perform repetitive tasks and can tirelessly do
a task tens of thousands of times.
• These sequences are easily processed by iteration statement blocks. Such
programming statements are called loops, because the flow of execution “loops
back” to the beginning of the block.
The while Loop
Java while loops statement allows to repeatedly run the same block of code
until a condition is met
• The syntax:
while (condition)
{
// Loop body
Statement(s);
65
}
public class Sample {
66
The do-while Loop
• Java do-while loops are very similar to the while loops, but it
always executes the code block at least once and furthermore as
long as the condition remains true.
• Syntax :
do {
// Loop body;
Statement(s);
} while (loop-continuation-condition);
• Executes the loop body first, then checks the loop-
continuation-condition to determine whether to continue or
terminate the loop. 67
public class Sample {
do {
System.out.println("Java do
while loops:" + n);
n++;
} while (n <= times);
}}
68
The for Loop
• Java for loops is very similar to Java while loops in that it
continues to process a block of code until a statement becomes
false, and everything is defined in a single line.
• A for loop can be used to simplify the proceeding loop:
70
Method in Java
• A method is a collection of statements that are grouped together to
perform an operation.
• You can pass data, known as parameters, into a method.
• Methods are used to perform certain actions, and they are also
known as functions.
• Why use methods?
o To reuse code:
o define the code once, and
o use it many times.
• For example, if we have a class Human, then this class should
have methods like eating(), walking(), talking() etc, which
describes the behavior of the object.
71
Declaring a Method
• A method must be declared within a class.
• It is defined with the name of the method, followed by
parentheses ().
• Java provides some pre-defined methods, such
as System.out.println(), but
• you can also create your own methods to perform certain actions:
syntax to declare the method in Java
return-type methodName(parameter-list)
{
//body of method
}
72
• Return Type : A method may return value. Data type of value return by
a method is declare in method heading.
• Method name : Actual name of the method.
• Parameter : Value passed to a method.
• Method body : collection of statement that defines what method does.
Calling a Method
• Methods are called to perform the functionality implemented in it.
• We can call method by its name and store the returned value into a
variable.
• write the method's name followed by two parentheses () and a semicolon;
Syntax methodName ();
73
public class Main {
static void myMethod() {
System.out.println("I just got executed!");
}
public static void main(String[] args) {
myMethod();
myMethod();
myMethod();
}}
74
Parameters and Arguments
• Parameter is variable defined by a method that receives value
when the method is called.
• Parameter are always local to the method they don’t have scope
outside the method. While
• argument is a value that is passed to a method when it is called.
• You can add as many parameters as you want, just separate them
with a comma.
75
When a parameter is passed to the method, it is called
an argument.
So, from the example above: fname is a parameter,
while Liam, Jenny and Anja are arguments.