Uploaded by Matebe Aragaw

Object Oriented Programming

advertisement
Contents
DEPARTMENT OF COMPUTER SCIENCE
Object Oriented Programming
Prepared By Haftom B. (M.Sc..)
1 1
Object Oriented Programming - By Haftom Berhe
}
Chapter One
Assessment
Methods
Exception
Chapter
Two
Classes Handling
and
Objects
Collection
Classes
Chapter
5643 Packages
} Introduction
to
Object-Oriented
Programming
1.
Test
1
10%
The aCollections
Framework
6.1.5.1.
2.1Inheritance
Defining
class
3.
and paradigms
Polymorphism
4.1.
Overview
Packages
} Types
ofExceptions
programming
2.
6.2. Test
The2Set 10%
Interface
2.2 } Overview
Creating
an
Object
•Project
Inheritance
of OO
principles
4.2.
Catching
Exceptions
3.
20%
The
import
6.3.5.2.
Set Implementation
Classes Statement
Editing,
Compiling
and
Interpreting
}
4.
10%
2.3 Instantiating
and
using
• The
Casting
6.4.Assignment
The
Listfinally
Interface
4.3.
Blockobjects
5.3.
Static
Imports
6.5.Final
List 50%
Implementation Classes
5.
2.4 Instance
fieldsInterface
• Exception
Method
Overriding
and Overloading
6.6.5.4.
The Queue
4.4.
Methods
CLASSPATH
and
Import
Text Book.
2.5
Constructors
and
Methods
Polymorphism
6.7.• Queue
Implementation
Classes
• Herbert
Schildt:
“Java 2,Exceptions
A Beginner’s
4.5.
Declaring
Defining
PackagesGuide”, 2ndedition, Tata
6.8.5.5.
The Map
Interface
2.6
Access
Modifiers
•
The
Object
Class
McGraw-Hill,
6.9.
Map 2003.
Implementation
Classes
4.6.
Defining
and
Throwing
tions
5.6.
Scope
•2.7
H. M.
Deitel
andPackage
P. J. Deitel:
“Java, How ExcepDRAFT
to Program”, 8th edition,
Encapsulation
• Abstract
Classes
New4.7.
Delhi,Errors
2012. and Runtime Exceptions
• Interfaces
• Using Interfaces
2
Object Oriented Programming - By Haftom Berhe
1.1 Introduction to Object-Oriented Programming
Chapter One
}
Types of programming paradigms
}
Overview of Java Programming
}
Editing, Compiling and Interpreting
Introduction to Object-Oriented Programming
}
3
Object Oriented Programming - By Haftom Berhe
4
Basics in Java Programming
Object Oriented Programming - By Haftom Berhe
Types of programming paradigms
aParadigm
can also be termed as method to solve some problem
Cont..
aThere
them need to follow some strategy when they are implemented
or do some task.
aProgramming
and this methodology/strategy is paradigms.
paradigm is an approach to solve problem using
some programming language or
aProgramming
are lots for programming language that are known but all of
Apart from varieties of programming language there are lots of
a
paradigms to fulfill each and every demand.
paradigms refer to the fundamental styles of
programming.
5
Object Oriented Programming - By Haftom Berhe
6
Object Oriented Programming - By Haftom Berhe
Cont..
}
Imperative programming consists of sets of detailed instructions
that are given to the computer to execute in a given order.
}
It's called "imperative" because as programmers we dictate exactly
what the computer has to do, in a very specific way.
}
Imperative programming focuses on describing how a program
operates, step by step
7
Object Oriented Programming - By Haftom Berhe
8
Object Oriented Programming - By Haftom Berhe
Cont.…
}
Overview of Java Programming
Declarative programming is all about hiding away complexity and
§
bringing programming languages closer to human language and
§
thinking.
§
It's the direct opposite of imperative programming in the sense
}
§
that the programmer doesn't give instructions about how the
computer should execute the task, but rather on what result is
§
needed.
9
Object Oriented Programming - By Haftom Berhe
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
GUIs,
file I/O
establishing network comm.
10
¨
}
11
The Java Virtual Machine (JVM)
} Is in charge of executing your code in a specific environment.
Object Oriented Programming - By Haftom Berhe
Object Oriented Programming - By Haftom Berhe
Features of Java (Java Buzzwords)
}
}
}
}
¨ creating
¨ performing
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.
}
}
Simple: Learning and practicing Java is easy because of resemblance with C
and C++.
Object Oriented: Unlike C++, Java is purely OOP.
Distributed: Java is designed for use on network; it has an extensive library
which works in agreement with TCP/IP.
Secure: Java is designed for use on Internet. Java enables the construction of
virus-free, tamper free systems.
Robust (Strong/ Powerful): Java programs will not crash because of its
exception handling and its memory management features.
Portable: Java does not have implementation dependent aspects and it gives
same result on any machine.
12
Object Oriented Programming - By Haftom Berhe
Contd…
}
}
}
}
}
Java Program Structure
Interpreted: Java programs are compiled to generate the byte code(.class
file). This byte code can be interpreted by the interpreter contained in JVM.
Architectural Neutral Language: Java byte code is not machine
dependent, it can run on any machine with any processor and with any OS.
High Performance: Along with interpreter there will be JIT (Just In Time)
compiler which enhances the speed of execution.
Multithreaded: Executing different parts of a program simultaneously is
called multithreading. This is an essential feature to design server side
programs.
Dynamic: We can develop programs in Java which dynamically change on
Internet (e.g.: Applets).
§
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
// comments about the class
public class MyProgram{
// comments about the method
public static void main (String[] args){
method body
13
Object Oriented Programming - By Haftom Berhe
Editing, Compiling and Interpreting
•
There are many tools to do java programming, to the very least you need to
have:
•
•
•
Object Oriented Programming - By Haftom Berhe
}
}
Object Oriented Programming - By Haftom Berhe
The Compiler and the Java Virtual Machine
§
Sun Java Development Kit (JDK Recent version)
Text editor such as Microsoft Notepad
Integrated Development Environment IDE for Java
} NetBeans (from Sun/Oracle)
} BlueJ
} Eclipse (from IBM)
} JCreator
} Borland JBuilder
} DrJ
} IntelliJ
} Android Studio and others
15
14
§
16
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 - By Haftom Berhe
The Compiler and the Java Virtual Machine…
§
§
§
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, a
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.
§
§
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 instructions are the machine language of the Java Virtual
Machine (JVM) and cannot be directly executed by the CPU.
}
}
}
Source File
17
Compiler
Object File
Linker
Excutable File
§
Object Oriented Programming - By Haftom Berhe
§
§
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 compiled and interpreted language.
18
Compiling Java Source Code
§
Byte code files end with the .class file extension.
Object Oriented Programming - By Haftom Berhe
Program Development Process
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
Saves Java statements
Text editor
Produces
Java compiler
Source code
(.java)
Byte code
(.class)
Java Bytecode
Java Virtual
Machine
Java
Virtual
Machine
Any
Computer
19
Object Oriented Programming - By Haftom Berhe
20
Results in
Program
Execution
Object Oriented Programming - By Haftom Berhe
Multiple Compilers
§
Java Interpreter
Because different operating systems (Windows, Macs, Unix) require
different machine code, you must compile most programming languages
separately for each platform.
§
§
§
Java is a little different.
Java compiler produces bytecode not machine code.
Bytecode can be run on any computer with the Java interpreter installed.
program
compiler
compiler
compiler
Unix
Win
21
MAC
Object Oriented Programming - By Haftom Berhe
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!");
}
}
22
Compiling and Running Your First Program
§
§
§
§
§
§
Save this file as HelloWorld.java (watch capitalization) in the
following directory: c:\java
23
Object Oriented Programming - By Haftom Berhe
Object Oriented Programming - By Haftom Berhe
§
24
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
Object Oriented Programming - By Haftom Berhe
Creating, Compiling, and Running Programs
Types of Java Program
§
Create/Modify Source Code
Source code (developed by the programmer)
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
Byte code (generated by the compiler for JVM
to read and interpret, not for you to understand)
…
Method Welcome()
0 aload_0
…
Method void main(java.lang.String[])
0 getstatic #2 …
3 ldc #3 <String "Welcome to
Java!">
5 invokevirtual #4 …
8 return
Saved on the disk
Source Code
§
Compile Source Code
i.e., javac Welcome.java
§
If compilation errors
stored on the disk
Bytecode
§
Run Byteode
i.e., java Welcome
All Java programs can be classified as Applications and
Applets.
Java applications are large programs that run standalone, with the support of a virtual machine.
Applet is a relatively small Java program executed by
web browser (inside an appletviewer).
Applets are great for creating dynamic and interactive
web applications
Result
If runtime errors or incorrect result
25
Object Oriented Programming - By Haftom Berhe
Types of Java Program…
26
Types of Java Program…
Applets on client-side and servlets on server-side
makes Java a truly "Internet-based language".
} To execute applets, the browsers come with JRE (Java
Runtime Environment).
} The browsers with Java Runtime Environment (or to
say, JVM) loaded are known as Java enabled browsers.
} Note: Browser do not have a Java compiler as a
compiled applet file (.class file) is given to browser to
execute.
}
27
28
}
Object Oriented Programming - By Haftom Berhe
Object Oriented Programming - By Haftom Berhe
}
}
}
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).
Object Oriented Programming - By Haftom Berhe
Types of Java Program…
Basics in Java Programming
§
29
§
Short Review
Java applications must have a main method.
}
For every left brace, or opening brace, there must be a
corresponding right brace, or closing brace.
}
Every java statements are terminated with semicolons.
}
Comments, class headers, method headers, and braces are
not considered as Java statements.
}
31
All Java programs must be stored in a file with a .java file extension.
}
Comments are ignored by the compiler.
}
A .java file may contain many classes but may only have one public class.
}
If a .java file has a public class, the class must have the same name as the file.
Object Oriented Programming - By Haftom Berhe
Java Identifiers
§
}
}
30
Object Oriented Programming - By Haftom Berhe
Basics in Java Programming…
Short Review
§
§
All java components requires names
Names used for classes, Variables and methods are called identifiers.
What is a Variable?
} Variables are places where information can be stored while a program
is running.
} Place holder in a memory
} Their values can be changed at any point over the course of a
program.
Don’t need semicolons
Object Oriented Programming - By Haftom Berhe
32
Object Oriented Programming - By Haftom Berhe
Creating Variables
§
§
§
Creating Variables…
To create a variable, declare its name and the type of information that it
will store.
The type is listed first, followed by the name.
Example: a variable that stores an integer representing the highest score
on an exam could be declared as follows:
§
§
}
Now you have the variable (highScore), you will want to assign a
value to it.
Example: the highest score in the class exam is 98.
highScore = 98;
Examples of other types of variables:
String studentName;
boolean gameOver;
int
highScore ;
type
name
33
Object Oriented Programming - By Haftom Berhe
Naming Variables
§
§
§
§
The name that you choose for a variable is called an identifier.
In Java, an identifier can be of any length, but must start with:
§
§
The rest of the identifier can include any character except those
used as operators in Java such as + , - , * .
In addition, there are certain keywords reserved (e.g., "class") in
the Java language which can never be used as identifiers.
see Reserved words
35
Object Oriented Programming - By Haftom Berhe
Naming Variables…
a letter (a – z, A-Z),
a dollar sign ($),
or, an underscore ( _ ).
§
34
Object Oriented Programming - By Haftom Berhe
Java is a case-sensitive language – the capitalization of letters
in identifiers matters.
A rose is not a Rose is not a ROSE
It is good practice to select variable names that give a good
indication of the sort of data they hold
§ For example,
§
36
if you want to record the size of a hat, hatSize is a good choice
for a name where as qqq would be a bad choice
Object Oriented Programming - By Haftom Berhe
Naming Variables…
§
§
POP QUIZ
When naming a variable, the following convention is commonly used:
}
The first letter of a variable name is lowercase
}
Each successive word in the variable name begins with a capital letter
}
All other letters are lowercase
Here are some examples:
pageCount
loadFile
anyString
threeWordVariable
37
Object Oriented Programming - By Haftom Berhe
Variables and value Assignments
One way is to declare a variable and then assign a
value to it with two statements:
int e; // declaring a variable
e = 5; // assigning a value to a variable
§ Another way is to write a single initialization
statement:
int e = 5; // declaring AND assigning
§
39
Object Oriented Programming - By Haftom Berhe
—
Which of the following are valid variable names?
1)$amount
2)6tally
3)my*Name
4)salary+
5)_score
6)first Name
7)total#
38
Object Oriented Programming - By Haftom Berhe
Read Statement
§ Used to assign value for variables interactively through the keyboard
using the readLine() method which belongs to the DataInputStream class.
§ The readLine() method reads the input from the keyboard as a string
which is then converted into the corresponding data type using the
data type wrapper classes.
§ The wrapper classes are contained in the java.lang package.
§ Wrapper classes wrap a value of the primitive types into an object.
§ The keywords try and catch are used to handle any errors that might
occur during the reading process.
40
Object Oriented Programming - By Haftom Berhe
Scope of Variables
1. Instance Variables: are declared in a class, but outside a method, constructor or
Java is a Strongly-Typed Language
§
any block.
• are created when an object is created with the use of the key word 'new' and destroyed when
the object is destroyed.
§
• They take different values for each object
2. Class Variables: are also known as static variables, are declared with the static
keyword in a class, but outside a method, constructor or a block.
• Are global to a class and belong to the entire set of objects that class creates.
• Only one memory location is created for each class variable.
§
§
All variables must be declared with a data type before they are
used.
Each variable's declared type does not change over the course
of the program.
Certain operations are only allowed with certain data types.
If you try to perform an operation on an illegal data type (like
multiplying Strings), the compiler will report an error.
3. Local Variables: are variables declared and used inside methods.
• Can also be declared inside program blocks that are define between { and }.
41
Object Oriented Programming - By Haftom Berhe
Primitive Data Types
Object Oriented Programming - By Haftom Berhe
Integer Data Types
There are eight built-in (primitive) data types in the Java language
} 4 integer types (byte, short, int, long)
} 2 floating point types (float, double)
} Boolean (boolean)
} Character (char)
} What Is the difference between byte, short, int, long and float
,Double ?
**see Appendix II: Summary of Primitive Data Types for a complete
table of sizes and formats**
} Appendix II: Primitive Data Types
§
43
42
Object Oriented Programming - By Haftom Berhe
§
§
§
There are four data types that can be used to store integers.
The one you choose to use depends on the size of the number that we want
to store.
Data Type
Value Range
byte
-128 to +127
short
-32768 to +32767
int
-2147483648 to +2147483647
long
-9223372036854775808 to +9223372036854775807
In this course, we will mostly use int when dealing with integers.
44
Object Oriented Programming - By Haftom Berhe
Integer Data Types…
§
Here are some examples of when you would want to use integer types:
- byte
-
smallValue;
smallValue = -55;
int pageCount = 1250;
Int result=35214; ?
-
long
}
Note: By adding an L to the end of the value in the last example, the
program is “forced” to consider the value to be of a type long even
if it was small enough to be an int
-
45
Object Oriented Programming - By Haftom Berhe
Here are some examples of when you would want to use
floating point types:
}
}
}
§
§
There are two data types that can be used to store decimal values
(real numbers).
The one you choose to use depends on the size of the number
that we want to store.
bigValue = 1823337144562L;
Floating Point Data Types…
§
Floating Point Data Types
double
g = 7.7e100 ;
double tinyNumber = 5.82e-203;
float costOfBook = 49.99F;
§
Data Type
Value Range
float
1.4×10-45 to 3.4×1038
double
4.9×10-324 to 1.7×10308
In this course, we will always use double when dealing with decimal
values.
46
Object Oriented Programming - By Haftom Berhe
Boolean Data Type
§
§
Boolean is a data type that can be used in situations where
there are two options, either true or false.
Example:
§ boolean monsterHungry = true;
§ boolean fileOpen = false;
§ Note: In the last example we added an F to the end of the value.
Without the F, it would have automatically been considered a
double instead.
47
Object Oriented Programming - By Haftom Berhe
48
Object Oriented Programming - By Haftom Berhe
Character Data Types
Introduction to Strings
}
Character is a data type that can be used to store a single
characters such as a letter, number, punctuation mark, or other
symbol.
Example:
§
§
}
}
}
String coAuthor = "John Smith";
String password = "swordfish786";
}
char firstLetterOfName = 'e' ;
char myQuestion = '?' ;
}
Note that you need to use single quotation marks when assigning
char data types.
§
49
Object Oriented Programming - By Haftom Berhe
Strings are not one of the primitive data types, although they are very
commonly used.
Strings are constant; their values cannot be changed after they are
created.
50
POP QUIZ
}
Strings consist of a series of characters inside double quotation marks.
Examples statements assign String variables:
Object Oriented Programming - By Haftom Berhe
Java Tokens
What data types would you use to store the following types of
information?
1)Population of Ethiopia
2)Approximation of π
3)Open/closed status of a file
4)Your name
5)First letter of your name
6)$237.66
int
double
boolean
String
char
double
}
A class in java is defined by a set of declaration statements and methods containing
executable statements.
}
Most statements contain expressions, which describe the actions carried out on
data.
}
Smallest individual units in a program are known as tokens.
}
In simplest terms, a java program is a collection of tokens, comments, and white
spaces.
}
Java has five types of tokens: Reserved Keywords, Identifiers, Literals, Separators and
Operators .
51
Object Oriented Programming - By Haftom Berhe
52
Object Oriented Programming - By Haftom Berhe
1. Keywords
}
}
2. Identifiers
Are essential part of a language definition and can not be used as names for variables,
classes, methods and so on.
Java language has reserved 60 words as keywords.
}
Are programmer-designed tokens.
}
Are used for naming classes, methods, variables, objects, labels, packages and
interfaces in a program.
}
53
Object Oriented Programming - By Haftom Berhe
Java identifiers follow the following rules:
}
They can have alphabets, digits, and the underscore and dollar sign characters.
}
They must not begin with a digit
}
Uppercase and lowercase letters are distinct.
}
They can be of any length.
54
Object Oriented Programming - By Haftom Berhe
4. Separators
3. Literals
}
Literals in Java are a sequence of characters(digits, letters and other
characters) that represent constant values to be stored in variables.
}
Five major types of literals in Java:
}
Are symbols used to indicate where groups of code are divided and arranged.
}
They basically define the shape and functions of our code.
}
I. Integer Literals: refers to a sequence of digits (decimal integer, octal
Java separators include:
I. Parenthesis ( ) :- used to enclose parameters, to define precedence in
integer and hexadecimal integer)
expressions, surrounding cast types
II. Floating-point Literals
II. Braces { } :- used to contain the values of automatically initialized arrays and to
III. Character Literals
define a block of code for classes, methods and local scopes.
IV.String Literals
V. Boolean Literals
55
Object Oriented Programming - By Haftom Berhe
56
Object Oriented Programming - By Haftom Berhe
Contd…
5. Operators
}
III. Brackets [ ] :- are used to declare array types and for dereferencing array
Are symbols that take one or more arguments (operands) and operates on
them to a produce a result.
values.
IV. Semicolon ; :- used to separate statements.
V. Comma , :- used to separate consecutive identifiers in a variable declaration,
also used to chain statements together inside a “for” statement.
}
Are used to in programs to manipulate data and variables.
}
They usually form a part of mathematical or logical expressions.
}
Expressions can be combinations of variables, primitives and operators
that result in a value.
VI. Period . :- Used to separate package names from sub-package names and
classes; also used to separate a variable or method from a reference variable.
57
Object Oriented Programming - By Haftom Berhe
Operators
}
}
}
}
mathematical functions
assignment statements
logical comparisons
• Examples:
3 + 5
14 + 5 – 4 * (5 – 3)
// uses + operator
// uses +, -, * operators
Expressions can be combinations of variables, primitives and operators that
result in a value
59
There are 5 different groups of operators:
Operators are special symbols used for:
}
}
Object Oriented Programming - By Haftom Berhe
The Operator Groups
What are Operators?
}
58
Object Oriented Programming - By Haftom Berhe
}
Arithmetic operators
}
Assignment operator
}
Increment/Decrement operators
}
Relational operators
}
Conditional operators
60
Object Oriented Programming - By Haftom Berhe
Arithmetic Operators
}
}
Order of Operations
Java has 6 basic arithmetic operators
+
add
subtract
*
multiply
/
divide
%
modulo (remainder)
^
exponent (to the power of)
Order of operations (or precedence) when evaluating an expression is the
same as you learned in school (PEMDAS).
61
}
}
}
Object Oriented Programming - By Haftom Berhe
Example: 10 + 15 / 5;
The result is different depending on whether the addition or
division is performed first
(10 + 15) / 5 = 5
10 + (15 / 5) = 13
Without parentheses, Java will choose the second case
Note: you should be explicit and use parentheses to avoid
confusion
62
Integer Division
Object Oriented Programming - By Haftom Berhe
Integer Division…
}
In the previous example, we were lucky that
gives an exact integer answer (5).
(10 + 15) / 5
}
But what if we divide 63 by 35?
}
Depending on the data types of the variables that store the
numbers, we will get different results.
§
Example
—
—
—
63
Object Oriented Programming - By Haftom Berhe
64
int i = 63;
int j = 35;
System.out.println(i / j);
Output: 1
double x = 63;
double y = 35;
System.out.println(x / y);
Ouput: 1.8
The result of integer division is just the integer part of the quotient!
Object Oriented Programming - By Haftom Berhe
Assignment Operator
}
Increment/Decrement Operators
The basic assignment operator (=) assigns the value of var to expr
count = count + 1;
can be written as:
++count; or count++;
++ is called the increment operator.
count = count - 1;
can be written as:
--count; or count--;
-- is called the decrement operator.
var = expr ;
}
}
Java allows you to combine arithmetic and assignment operators into a single
operator.
Examples:
x = x + 5;
is equivalent to
x += 5;
y = y * 7;
is equivalent to y *= 7;
65
Object Oriented Programming - By Haftom Berhe
The increment/decrement has two forms:
66
Relational (Comparison) Operators
}
}
The prefix form ++count, --count
first adds 1 to the variable and then continues to any other operator in the expression
}
Relational operators compare two values
Produces a boolean value (true or false) depending on the relationship
int numOranges = 5;
int numApples = 10;
int numFruit;
numFruit = ++numOranges + numApples;
numFruit has value 16
numOranges has value 6
}
67
Object Oriented Programming - By Haftom Berhe
operation
is true when . . .
a > b
a is greater than b
a >= b
a is greater than or equal to b
The postfix form count++, count-first evaluates the expression and then adds 1 to the variable
a == b
a is equal to b
a != b
a is not equal to b
int numOranges = 5;
int numApples = 10;
int numFruit;
numFruit = numOranges++ + numApples;
numFruit has value 15
numOranges has value 6
a <= b
a is less than or equal to b
Object Oriented Programming - By Haftom Berhe
a < b
68
a is less than b
Object Oriented Programming - By Haftom Berhe
Examples of Relational Operations
Conditional Operators
int x = 3;
int y = 5;
boolean result;
1.
result = (x > y);
now result is assigned the value false because 3 is not greater than 5
2.
}
result = (15 == x*y);
now result is assigned the value true because the product of
3 and 5 equals 15
3.
Symbol
Name
&&
AND
||
OR
!
NOT
Conditional operators can be referred to as boolean operators, because
they are only used to combine expressions that have a value of true or
false.
result = (x != x*y);
now result is assigned the value true because the product of
x and y (15) is not equal to x (3)
69
Object Oriented Programming - By Haftom Berhe
Truth Table for Conditional Operators
70
Object Oriented Programming - By Haftom Berhe
Examples of Conditional Operators
boolean x = true;
boolean y = false;
boolean result;
1.
Let result = (x && y);
now result is assigned the value false
(see truth table!)
2.
Let result = ((x || y) && x);
(x || y)
(true && x)
evaluates to true
evaluates to true
now result is assigned the value true
71
Object Oriented Programming - By Haftom Berhe
72
Object Oriented Programming - By Haftom Berhe
Using && and ||
}
Examples
(a && (b++ > 3))
What happens if a is false?
} Java will not evaluate the right-hand expression (b++ > 3) if the lefthand operator a is false, since the result is already determined in this
case to be false. This means b will not be incremented!
(x || y)
What happens if x is true?
} Similarly, Java will not evaluate the right-hand operator y if the left-hand
operator x is true, since the result is already determined in this case to
be true.
Examples:
(a && (b++ > 3))
(x || y)
}
Java will evaluate these expressions from left to right and so will evaluate
a before (b++ > 3)
x before y
}
Java performs short-circuit evaluation:
it evaluates && and || expressions from left to right and once it finds the
result, it stops.
73
Object Oriented Programming - By Haftom Berhe
74
Object Oriented Programming - By Haftom Berhe
Fundamental Principles of OOP
POP QUIZ
1.
1) What is the value of result?
int x = 8;
int y = 2;
boolean result = (15 == x * y);
2) What is the value of result?
boolean x = 7;
boolean result = (x < 8) && (x > 4);
2.
3.
false
4.
5.
true
6.
3) What
int
int
int
75
is the value of numCars?
numBlueCars = 5;
numGreenCars = 10;
27
numCars = numGreenCars++ + numBlueCars + ++numGreeenCars;
Object Oriented Programming - By Haftom Berhe
7.
76
Objects
Classes
Methods and Messages
Abstraction
Inheritance
Encapsulation
Polymorphism
Object Oriented Programming - By Haftom
Berhe
OOP Concepts
§
§
§
§
Object Examples
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).
77
Object Oriented Programming - By Haftom
Berhe
Class
§
§
§
§
§
§
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
78
Object Oriented Programming - By Haftom
Berhe
Methods
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:
§ Dog #1 is a black Poodle,
class Dog {
§ Dog #2 is a red Irish Setter
§
§
§
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()
{
// state and behavior
...
}
}
}
79
Object Oriented Programming - By Haftom
Berhe
80
Object Oriented Programming - By Haftom
Berhe
Message
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 as specialization.
§
§
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.
§
§
§
81
Object Oriented Programming - By Haftom
Berhe
Object Oriented Programming - By Haftom
Berhe
Inheritance – Benefits
Inheritance
§
82
Inheritance terminology
derived class
class
derived interface
inherits
implements
implements
base class /
parent class
interface
base interface
E.g. A old style television (idiot box) is transformed with extra features into slim
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)
§
and smart television where it re-used the properties of old television.
83
Object Oriented Programming - By Haftom
Berhe
84
Object Oriented Programming - By Haftom
Berhe
Encapsulation
Inheritance – Example
.
Base class
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.
§
Person
+Name: String
+Address: String
§
§
Derived class
Derived class
Employee
Student
+Company: String
+Salary: double
85
+School: String
§
§
§
§
§
86
Object Oriented Programming - By Haftom
Berhe
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
Object Oriented Programming - By Haftom
Berhe
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 à a getter method and
§
For write-only à a setter method will be used.
§
§
-name : String
§
-age : TimeSpan
§
+Person (String name, int age)
+Name : String { get; set; }
+Age : TimeSpan { get; set; }
87
Object Oriented Programming - By Haftom
Berhe
88
Object Oriented Programming - By Haftom
Berhe
Polymorphism
§
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
}
}
§
89
Object Oriented Programming - By Haftom
Berhe
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
90
Object Oriented Programming - By Haftom
Berhe
Abstraction
Polymorphism
Figure
.
Abstract
action
Abstraction is a process of hiding the implementation details and showing only
§
functionality to the user.
+CalcSurface() : double
Concrete
class
Overriden
action
Square
-x : int
-y : int
-size : int
override CalcSurface()
{
return size * size;
}
91
Abstraction means hiding internal details and showing the required things.
§
Circle
-x : int
-y : int
-radius: int
Overriden
action
override CalcSurface()
{
return PI * radius * raduis;
}
Object Oriented Programming - By Haftom
Berhe
}
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 achieve abstraction in two ways:
}
92
abstract class (0 to 100%) and interface (100%).
Object Oriented Programming - By Haftom
Berhe
Outlines
§
§
Defining a class
Creating an Object
§ Instantiating and using objects
§ Printing to the Console
§ Methods and Messages
CHAPTER TWO
§
§ Access Modifiers by method
Parameter Passing
Comparing and Identifying Objects
§
Instance fields
§
Constructors and Methods
§
Classes and Object
Destroying Objects
Encapsulation
§
§
§
93
Object Oriented Programming - By Haftom Berhe
Enumerated Types
94
Object Oriented Programming - By Haftom
Berhe
Contd.
Defining a Class
§ A class is a user-defined data type with a template that serves to define its
§ Everything inside the square brackets [ ] is optional. This means the following would
properties.
§ Once a class type has been defined, we can create “variables” of that type
using declaration that are similar to the basic type declarations.
§ In Java such variables are known as instance variables, which are the actual
objects.
§ The basic form of a class definition is:
class classname [extends superclassname]
{
[ variable declaration; ]
[ methods declaration; ]
}
95
Object Oriented Programming - By Haftom Berhe
be a valid class definition:
class Empty
{
}
§ classname and superclassname are any valid Java identifiers.
§ The keyword extends indicates that the properties of the superclassname class are
extended to the classname class.This concept is known as inheritance.
96
Object Oriented Programming - By Haftom Berhe
Adding Variables (Fields)
Cont.…
}
A class declaration consists of:
1.
2.
3.
4.
5.
§ Data is encapsulated in a class by placing data fields inside the body of the class definition.
Modifiers: Can be public or default access.
Class name: Initial letter.
Superclass: A class can only extend (subclass) one parent.
Interfaces: A class can implement more than one interface.
Body: Body surrounded by braces, { }.
§ These variables are called instance variables (member variables) because they are created
when an object of the class is instantiated.
§ These variables are created exactly the same way as we declare local variables.
Example:
AccessModifier class ClassName { //defines class
AccessModifier Type variableName; //declares class variables
…….
AccessModifier retrunType methodName(arguments){
class Rectangle
{
int length;
//defines class methods
int width;
return values;
97
} //end of method
} //end of class
Object Oriented Programming - By Haftom
Berhe
}
98
Contd.
Adding Methods
§ A class with only data fields (and without methods that operate on
that data) has no life.
§ Method declaration has four parts:
i. The name of the method (methodname).
ii. The type of the value the method returns (type).
§ Methods are declared inside the body of the class but immediately
after the declaration of the instance variables.
§ The general form of a method declaration is:
iii. A list of parameters (parameter-list).
iv. The body of the method
§ The type specifies the type value the method would return. This could be a simple
data type such as int as well as any class type.
§ It could be void type, if the method does not return any value.
type methodname(parameter-list)
§ The methodname is a valid identifier.
{
§ The parameter-list is always enclosed in parenthesis and contains variable names and
method-body;
}
99
Object Oriented Programming - By Haftom Berhe
Object Oriented Programming - By Haftom Berhe
types of all the values we want to give to the method as input.
100
Object Oriented Programming - By Haftom Berhe
Contd.
}
}
}
}
Class - Example
Methods which act upon instance variables of a class are called
instance methods.
Instance variable is a variable whose separate copy is available in
every object.
Any modifications to instance variable in one object will not affect
the instance variable of other objects. These variables are created
on heap.
Instance methods can read and act upon static variables also.
class Rectangle
{
int length, width;
void getData(int x, int y)
// A method with two parameter
{
length=x;
width=y;
}
int rectArea() // A method with no parameter
{
return length*width;
}
}
101
Object Oriented Programming - By Haftom Berhe
Creating Objects
102
Object Oriented Programming - By Haftom Berhe
Contd.
Example:
}
An object in Java is essentially a block of memory that contains space to store all the
Rectangle R1 = new Rectangle();
instance variables.
Action
}
Creating an object also known as instantiating an object.
}
Objects in Java are created using the new operator.
}
The new operator creates an object of the specified class and returns a reference to
Declare
Rectangle R1
Instantiate
R1=new Rectangle
()
that object.
}
R1 is a reference to
Rectangle object
Syntax for object creation:
Statement
Result
null
.
Rectangle
object
classname objectname; //declares a variable to hold the object reference
objectname = new classname( ); // Assigns the object reference to the variable
103
Object Oriented Programming - By Haftom Berhe
104
Object Oriented Programming - By Haftom Berhe
R1
R1
Complete Example
Accessing class Members
}
}
To access members (fields and the methods) of an object, use the dot (.) operator
together with the reference to an object.
The general syntax is as follows:
class Student
{
int studid;
String studname;
objectname.variablename;
objectname.methodname(parameter-list);
Example:
R1.length=23;
R1.width=13;
a)
System.out.println(“Area is “+R1.rectArea();
void display( )
{
System.out.println(" Student id:
"+studid);
System.out.println(" Student Name:
"+studname);
class StudentDemo
{ public static void main(String args[])
{ Student s1 = new Student( );
s1.studid = 1201;
s1.studname = "AU";
s1.display();
Student s2 = new Student( );
s2.studid = 1202;
s2.studname = "ASTU";
s2.display();
}
}
}
}
R1.getData(34,15);
b)
System.out.println(“Area is “+ R1.rectArea();
105
Object Oriented Programming - By Haftom Berhe
Static Methods
}
}
}
}
}
}
Object Oriented Programming - By Haftom Berhe
Static Methods - Example
Static methods can read and act upon static variables.
Static methods cannot read and act upon instance variables.
Static variable is a variable whose single copy is shared by all the objects.
Static methods are declared using keyword static.
Static methods can be called using
objectname.methodname (or)
classname.methodname
From any object, if static variable is modified it affects all the objects. Static
variables are stored on method area.
107
106
Object Oriented Programming - By Haftom Berhe
//static method accessing static variable
class Sample
{ static int x = 10;
static void display( )
{ x++;
System.out.println (" x value is = " + x);
}
}
class SDemo
{ public static void main(String args[])
{ System.out.print(“Calling static method using Class name:“);
Sample.display ();
Sample s1 = new Sample ( );
System.out.print(“Calling static method using Object name:“);
s1.display ();
}
Object Oriented Programming - By Haftom Berhe
} 108
Constructors
}
Rules with Constructors
It is possible to initialize objects, they are created by:
}
}
}
Using the dot operator
The help of methods
Class name and constructor name should be the same. That is, it has the same name as
the class in which it resides and is syntactically similar to a method.
}
But it would be simpler and more concise to initialize an object when it is first created.
}
Java supports a special type of method, called a constructor, that enables an object to
}
Constructors have no return type (not even void), t his is because they return the
instance of the class itself.
}
Constructors should be public.
}
Constructors can not be inherited.
}
They can be overloaded. Many constructors with the same name can be defined.
initialize itself when it is created.
}
A constructor initializes an object immediately upon creation. But object creation only doesn’t
call constructor rather it will be called when the object is instantiated.
}
Call the constructor(s) preceding it with the new keyword.
109
Object Oriented Programming - By Haftom Berhe
Types of Constructors
110
Object Oriented Programming - By Haftom Berhe
Default Constructor
class Box {
1. Default constructor: is the type of constructor with out any argument.
double width;
2. Parameterized Constructor: is a constructor with one or more argument.
}
}
}
double height;
double depth;
When an instance of an object is created then the instance will call the
constructor.
Box()
// default constructor
{
It will be the default constructor which will be called, if there are no any
parameterized constructor.
System.out.println("Constructing Box");
width = 10; height = 10; depth = 10;
}
But if there is any parameterized constructor, then it will be the
parameterized constructor with the specified parameter(s) which will be
called.
double volume()
{
return width * height * depth;
}
111
Object Oriented Programming - By Haftom Berhe
112
}
Object Oriented Programming - By Haftom Berhe
Parameterized Constructor - Example
class Box {
double width;
double height;
double depth;
Box(double w, double h, double d)
{
width = w; height = h; depth = d;
}
double volume()
{ return width * height * depth;
}
}
113
Object Oriented Programming - By Haftom Berhe
A constructor can call another constructor with this(arguments)
class LightSwitch
{
boolean on;
LightSwitch() {
this(true);
}
LightSwitch(boolean on) {
this.on = on;
}
}
115
}
}
Can be used by any object to refer to itself in any class method
Typically used to
} avoid variable name collisions
} pass the receiver as an argument
} chain constructors
class LightSwitch
{
boolean on;
LightSwitch() {
this.on = true; //(same as on=true;)
}
LightSwitch(boolean on) {
this.on = on;
}
}
114
Object Oriented Programming - By Haftom Berhe
Apple Example
Cascading Constructors
}
this Keyword
Object Oriented Programming - By Haftom Berhe
class Apple {
String color;
double price;
Apple(String color, double price)
this.color = color;
this.price = price;
}
Apple(double price) {
this("green", price);
}
String getColor() { return color;
double getPrice() { return price;
void setPrice(double p) { price =
}
116
{
}
}
p; }
Object Oriented Programming - By Haftom Berhe
Apple Quiz
Access Control
What will these lines print out?
Apple a = new Apple("red", 100.0);
red
System.out.println(a.getColor());
100.0
}
Java provides control over the visibility of variables and methods.
}
Encapsulation, safely sealing data within the capsule of the class, prevents
System.out.println(a.getPrice());
programmers from relying on details of class implementation, so you can
50.5
a.setPrice(50.5);
update without worry.
System.out.println(a.getPrice());
Apple b = new Apple(74.6);
System.out.println(b.getColor());
green
System.out.println(b.getPrice());
74.6
}
Helps in protecting against accidental or wrong usage.
}
Keeps code elegant and clean (easier to maintain)
b.setPrice(a.getPrice());
System.out.println(b.getPrice());
117
50.5
Object Oriented Programming - By Haftom Berhe
An access specifier is a keyword that represents how to access a member of a class.
There are four access specifiers in java.
}
public class Circle
{
private double x, y, r;
public: keyword applied to a class, makes it available/visible everywhere. Applied
// Constructor
public Circle (double x, double y, double r)
{
this.x = x;
this.y = y;
this.r = r;
}
//Methods to return circumference and area
public double circumference() { return 2*3.14*r;}
public double area() { return 3.14 * r * r; }
to a method or variable, completely visible.
}
private: private fields or methods for a class only visible within that class.
Private members are not visible within subclasses, and are not inherited.
}
protected: protected members of a class are visible within the class, subclasses
and also within all classes that are in the same package as that class.
}
default (if no access specifier specified): it behaves like public in its package and
}
private in other packages.
119
Object Oriented Programming - By Haftom Berhe
Visibility - Example
Access Specifiers
}
118
Object Oriented Programming - By Haftom Berhe
120
Object Oriented Programming - By Haftom Berhe
Contd.
Method Overloading
}
}
}
It is legal for a class to have two or more methods with the same name.
However, Java has to be able to uniquely associate the invocation of a
method with its definition relying on the number and types of arguments.
Therefore the same-named methods must be distinguished:
}
}
}
}
}
by the number of arguments, or
by the types of arguments
By the sequence of arguments
Method overloading is resolved at compile time.
Overloading and inheritance are two ways to implement polymorphism.
121
Object Oriented Programming - By Haftom Berhe
Method Overloading - Example
class Sample{
void add(int a,int b)
{
System.out.println ("sum of two="+ (a+b));
}
void add(int a,int b,int c)
{
System.out.println ("sum of three="+ (a+b+c));
}
}
class OverLoad
{
public static void main(String[] args)
{ Sample s=new Sample ( );
s.add (20, 25);
s.add (20, 25, 30);
}
}
123
Object Oriented Programming - By Haftom Berhe
}
}
}
There is a difference in the no. of parameters.
}
void add (int a, int b)
}
void add (int a, int b, int c)
There is a difference in the data types of parameters.
}
void add (int a, float b)
}
void add (double a, double b)
There is a difference in the sequence of parameters.
}
void swap (int a, char b)
}
void swap (char a, int b)
122
Object Oriented Programming - By Haftom Berhe
Constructor Overloading
class Box
{
double width, height, depth;
Box(double w, double h, double d)
{
width = w; height = h; depth = d;
}
Box()
{
width = -1; height = -1; depth = -1;
}
Box(double len)
{
width = height = depth = len;
}
double volume()
{ return width * height * depth;
}
}
124
Object Oriented Programming - By Haftom Berhe
finalize() Method
Garbage Collection
}
}
}
}
Generally memory is allocated to objects by using ‘new’ operator and deleted
by ‘delete’ operator in C++.
But this deletion of allocated memory works automatically in Java.
Garbage collection is a mechanism to remove objects from memory when
they are no longer needed (unused memory).
Garbage collection is carried out by the garbage collector, gc( ):
}
}
}
}
}
}
}
A constructor helps to initialize an object just after it has been created.
In contrast, the finalize method is invoked just before the object is destroyed.
The Java runtime calls that method whenever it is about to recycle an object
of that class:
protected void finalize()
{
// finalization code here
}
The garbage collector keeps track of how many references an object has.
It removes an object from memory when it has no longer any references.
Thereafter, the memory occupied by the object can be allocated again.
The garbage collector invokes the finalize method.
125
Object Oriented Programming - By Haftom Berhe
126
Object Oriented Programming - By Haftom Berhe
Example
127
class garbage extends Object
{
int x,y;
void setdata(int a,int b)
{
x=a;
y=b;
}
void display()
{
System.out.println(“x="+x);
System.out.println("y="+y);
}
protected void finalize()
{
System.out.println(" finalize");
}
}
class gc
{
public static void main(String a[])
{
garbage obj1=new garbage();
garbage obj2=new garbage();
obj1.setdata(10,20);
obj1.display();
obj2=null;
System.gc();
//obj2.display();
Chapter Three
Inheritance and polymorphism
}
}
Object Oriented Programming - By Haftom Berhe
128
Object Oriented Programming - By Haftom Berhe
Introduction to Inheritance
Chapter Outlines
§
§
§
§
§
§
§
Introduction Inheritance
§ Super-classes and Sub-classes
§ Using the super Keyword
Method Overriding and Overloading
Polymorphism
Casting Objects and Instance Operator
The Object Class
Abstract Classes
Interfaces
§
In the real world:
§
We inherit traits from our mother and father.
§
We also inherit traits from our grandmother, grandfather, and ancestors.
§
We might have similar eyes, the same smile, a different height . . . but we are in many ways
"derived" from our parents.
§
In software:
§
Object inheritance is more well defined!
§
Objects that are derived from other object "resemble" their parents by inheriting both state
(fields) and behavior (methods).
129
Object Oriented Programming - By Haftom Berhe
Introduction to Inheritance
§
§
§
§
§
131
Object-oriented programming allows you to define new classes
from existing classes. This is called inheritance.
The procedural paradigm focuses on designing methods and the
object-oriented paradigm couples data and methods together into
objects.
Inheritance is an important and powerful feature for reusing
software.
what is the best way to design classes so as to avoid redundancy
and make then system easy to comprehend and easy to maintain.
The answer is to use inheritance.
Object Oriented Programming - By Haftom
Berhe
130
Object Oriented Programming - By Haftom
Berhe
Introduction to Inheritance
§ Super-classes and Sub-classes
§
§
§
§
132
Different classes may have some common properties and behaviors:§ which can be generalized in a class that can be shared by other
classes.
You can define a specialized class that extends the generalized class.
The specialized classes inherit the properties and methods from the
general class.
In Java terminology, a class C1 extended from another class C1 is called
a subclass, and C2 is called a superclass.
Object Oriented Programming - By Haftom
Berhe
Introduction to Inheritance
Introduction to Inheritance
§ Super-classes and Sub-classes
§ A superclass is also referred to as a parent class or a base class, and a subclass as a
child class, an extended class, or a derived class.
§ A subclass inherits accessible data fields and methods from its superclass and may
also add new data fields and methods.
§ The keyword “extends” used to create inheritance in java.
.
Dog
Cat
String name
int fleas
String getName()
int getFleas()
void speak()
String name
int hairballs
String getName()
int getHairballs()
void speak()
using
inheritance
superclas
s
Animal
subclass
String name
String getName()
subclass
Dog
int fleas
int getFleas()
void speak()
133
Object Oriented Programming - By Haftom
Berhe
Note the following points regarding inheritance:
§ Contrary to the conventional interpretation, a subclass is not a subset
of its superclass.
§ In fact, a subclass usually contains more information and methods than
its superclass.
§ Private data fields in a superclass are not accessible outside the class.
§ Therefore, they cannot be used directly in a subclass.
§ They can, however, be accessed/mutated through public accessors or
/mutators if defined in the superclass.
135
Object Oriented Programming - By Haftom
Berhe
Recap
Super-classes and Sub-classes
§
134
Cat
int hairballs
int getHairballs()
void speak()
Object Oriented Programming - By Haftom Berhe
1.
True or false? A subclass is a subset of a superclass.
2.
What keyword do you use to define a subclass?
3.
What is inheritance
136
Object Oriented Programming - By Haftom
Berhe
Using the super Keyword
§
§
§
§
Using the super Keyword
The keyword super refers to the superclass and can be used to invoke
the superclass’s methods and constructors.
A subclass inherits accessible data fields and methods from its
superclass.
It can be used in two ways:
§ To call a superclass constructor.
§ To call a superclass method.
To call superclass method we use super.method(parameters);
§
Calling Superclass Constructors:
§
§
§
§
A constructor is used to construct an instance of a class.
Unlike properties and methods, the constructors of a superclass are not
inherited by a subclass.
They can only be invoked from the constructors of the subclasses using the
keyword super.
The syntax to call a superclass’s constructor is:
Ü super(), or super(parameters);
public ClassName() {
// some statements
}
137
Object Oriented Programming - By Haftom
Berhe
Example
Object Oriented Programming - By Haftom Berhe
Example
public class Box {
public class Box {
§
138
Equivalent
public ClassName() {
super();
// some statements
}
Calling Superclass Constructors:
double width;
double height;
§ A constructor is used to construct an instance of a class.
double depth;
§ Unlike properties and methods, the constructors of a superclass are
// constructor used when no dimensions specified
not inherited by a subclass.
Box() {
width §= They
-1; //
indicate
canuse
only-1beto
invoked
from the constructors of the subclasses
height =using
-1; the
// keyword
an uninitialized
super.
depth = -1; // box
§ The syntax to call a superclass’s constructor is:
}
// constructor used
when all or
dimensions
specified
Ü super(),
super(parameters);
Box(double w, double h, double d) {
width = w; height = h; depth = d;
}
// compute and return volume
double volume() {
return width * height * depth;
}
} 139
Object Oriented Programming - By Haftom
Berhe
// BoxWeight now uses super to initialize its Box attributes.
double width;
public class
BoxWeight
extends
Box{
Superclass
Constructors:
§ Calling
double height;
double
depth;
§ A//constructor
used to construct an instance of a class.
double weight;
weight of isbox
§
Unlike properties and methods, the constructors of a superclass are
// constructor used when no dimensions specified
// default constructor
Box()not
{ inherited by a subclass.
BoxWeight() {
width
= -1;
use -1
to the
indicate
can only
be //
invoked
from
constructors of the subclasses
§ They
super();
height
= -1; //
an uninitialized
using
the
keyword
super.
weight = -1;
depth = -1; // box
}
} § The syntax to call a superclass’s constructor is:
// constructor
used when
all dimensions specified
Ü super(),
// initialize width,
height,or
andsuper(parameters);
depth using super()
Box(double w, double h, double d) {
BoxWeight(double w, double h, double d, double m) {
width = w; height = h; depth = d;
super(w, h, d); // call superclass constructor
}
weight = m;
// compute and return volume
}
double volume() {
}
return width * height * depth;
}
}
140
Object Oriented Programming - By Haftom
Berhe
Cont..
Recap
public class Box {
public class TestDemoSuper {
double width;
§ Calling
Constructors:
public static
void Superclass
main(String[]
args) {
double height;
double
depth;
§ A constructor
is
used
to construct an instance of a class.
BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);
properties
and methods,
the constructors of a superclass are
§ Unlike
BoxWeight mybox2
= new
BoxWeight();
// default
// constructor used when no dimensions specified
not
inherited
by
a
subclass.
Box() {
double vol;
width
= -1;
use -1
to the
indicate
§ They
can only
be //
invoked
from
constructors of the subclasses
vol= mybox1.volume();
height
= -1; //
an uninitialized
using
the keyword
super.
depth = -1; // box
System.out.println("Volume
of mybox1 is " + vol);
} § The syntax to call a superclass’s constructor is:
System.out.println("Weight of mybox1 is " + mybox1.weight);
// constructor
used
all dimensions specified
Ü super(),
orwhen
super(parameters);
System.out.println();
Box(double w, double h, double d) {
width = w; height = h; depth = d;
vol = mybox2.volume();
}
System.out.println("Volume of mybox2 is " + vol);
// compute and return volume
System.out.println("Weight of mybox2 is " + mybox2.weight);
double volume() {
System.out.println();
return width * height * depth;
}
}
}
}
141
Object Oriented Programming - By Haftom
1.
What is the output of running the class C in (a)? What problem arises in compiling the program in (b)?
public class A {
public A() {
System.out.println("A's no-arg constructor is invoked");
}
}
//sub class
class B extends A {}
public class C {
public static void main(String[] args) {
B b = new B();
}
}
142
Object Oriented Programming - By Haftom Berhe
Berhe
Types of Inheritance in Java
Single level Inheritance in Java
§
§
§
In single inheritance, one class inherits the properties of another.
It enables a derived class to inherit the properties and behavior from a single parent
class.
This will, in turn, enable code reusability as well as add new features to the existing
code.
Cat
143
Object Oriented Programming - By Haftom Berhe
144
Extends
Object Oriented Programming - By Haftom Berhe
Animal
Single level Inheritance in Java
Multi-level Inheritance in Java
class Animal {
public void eat(){System.out.println(“eating”);
§
In single inheritance, one class inherits
}
the
} properties of another.
class
Doga derived
extendsclass
Animal
{
It
enables
to inherit
the
void
properties
and bark(){
behavior from a single
System.out.println(“barking”);
parent class.
When a class is derived from a class which is also derived from another
class, i.e. a class having more than one parent class but at different levels,
such type of inheritance is called Multilevel Inheritance.
}
This
will, in turn, enable code
}
reusability
as well as add new
class TestInheritance
{ features
to
the existing
public
staticcode.
void main(String args[]) {
Extends
Extends
Dog d = new Dog();
d.bark();
d.eat();
Puppy
Dog
Animal
}
}
145
Object Oriented Programming - By Haftom Berhe
Cont..
146
Object Oriented Programming - By Haftom Berhe
Reminder
class Animal {
void eat(){
System.out.println(“eating…”);}
}
class Dog extends Animal {
void bark(){
System.out.println(“barking…”);}
}
class Puppy extends Dog {
void weep(){
System.out.println(“weeping…”);}
}
Extends
class TestInheritance2 {
public static void main(String args[]) {
Puppy d = new Puppy();
d.weep();
d.bark();
d.eat();
} }
147
Object Oriented Programming - By Haftom
Berhe
§
§
§
§
§
§
RULE 1: Multiple Inheritance is NOT permitted in Java.
RULE 2: Cyclic Inheritance is NOT permitted in Java.
RULE 3: Private members do NOT get inherited.
RULE 4: Constructors cannot be Inherited in Java.
RULE 5: In Java, we assign parent reference to child objects.
RULE 6: Constructors get executed because of super() present in the
constructor.
148
Object Oriented Programming - By Haftom
Berhe
Method Overriding and Overloading
§ Method Overriding
Method Overriding
§ Method Overriding
§
Re defining the method of the Super Class in the Sub Class.
§
Inheritance in java involves a relationship between parent and child classes.
§
Whenever both the classes contain methods with the same name and arguments or
parameters it is certain that one of the methods will override the other method
during execution.
§
Method will be called depending on the object.
§
Method overriding is achieved in Inheritance.
class super {
public void display() {
System.out.println(“Hello”);
}
}
class sub extends super {
public void display() {
System.out.println(“Hello Welcome”);
}
}
The same method display in super and sub class
149
Object Oriented Programming - By Haftom
Berhe
Method Overriding
§
§
§
§ Method Overriding
When the sub class object is called then the display method inherited from the super class is
shadowed and the sub class display method is executed.
Super Class method never be called upon the object of Sub Class.
In the given example program the super class have a method called display which is saying hello
and another class sub class is taken where it inherits the display method from super class and re
defines the method.
When a super class reference holding the object of sub class and overridden method is called
then method of object will be called it is Dynamic Method Dispatch.
§
§
§
§
§
§
§
151
Object Oriented Programming - By Haftom
Berhe
Method Overriding
§ Method Overriding
§
150
Object Oriented Programming - By Haftom
Berhe
152
Do’s and Don’ts of Overriding.
Signature must be same in method overriding.
If the method name is different the method is not overridden but it is
overloaded.
Argument may be different but the parameter must be same.
Return type must be same, if it is not same then the method is neither
overridden nor overloaded.
Final and static methods cannot be overridden.
Method can be overridden with same or lenient (public, protected) access
specifiers but the stricter(private) access specifiers cannot be used in sub class.
Object Oriented Programming - By Haftom
Berhe
§Method Overloading
Method Overloading
Overloading methods enables you to define the methods with the same name as long as their
signatures are different.
§ We cannot overload a return type.
§ Although we can overload static methods, the arguments or input parameters have to be different.
§ We cannot overload two methods if they only differ by a static keyword. Like other static methods,
the main() method can also be overloaded.
//method overloading
public static double max(double num1, double num2) {
if (num1 > num2) {
return num1;
} else {
return num2;
}
}
public static int max(int num1, int num2) {
if (num1 > num2) {
return num1;
} else {
return num2;
}
}
Method(X)
Same class
Method(X, Y)
•
You can have this three method in
single class
153
Method(X, Y, Z)
Object Oriented Programming - By Haftom
Berhe
154
Method Overloading
§
§
§
§
§
§
Object Oriented Programming - By Haftom
Berhe
Method Overloading Tips
Overloading methods can make programs clearer and more
readable.
Methods that perform the same function with different types of
parameters should be given the same name.
Overloaded methods must have different parameter lists.
You cannot overload methods based on different modifiers or
return types.
Sometimes there are two or more possible matches for the
invocation of a method, but the compiler cannot determine the best
match. This is referred to as ambiguous invocation.
Ambiguous invocation causes a compile error.
155
It also helps in compile-time
polymorphism.
§
Object Oriented Programming - By Haftom
Berhe
§
Consider the following code:
public class AmbiguousOverloading {
public static void main(String[] args) {
System.out.println(max(1, 2));
}
public static double max(int num1, double num2) {
if (num1 > num2)
return num1;
else
return num2;
}
public static double max(double num1, int num2) {
if (num1 > num2)
return num1;
else
return num2;
}
}
156
Object Oriented Programming - By Haftom
Berhe
ambiguous
invocation
Cont..
Polymorphism
Difference between Method Overloading and Method Overriding
Method Overloading
Method Overriding
§ It is used to increase the readability of the program
§ Provides a specific implementation of the method
already in the parent class
§ It is performed within the same class
§ It involves multiple classes
§ Parameters must be different in case of overloading
§ Parameters must be same in case of overriding
§ Is an example of compile-time polymorphism
§ It is an example of runtime polymorphism
§ Return type can be different but you must change the
parameters as well.
§ Return type must be same in overriding
§ Static methods can be overloaded
§ Overriding does not involve static methods.
§
Polymorphism means that a variable of a supertype can refer to a subtype object.
§
Assuming different forms. “Poly” means numerous, and “Morphs” means forms.
§
Polymorphism means that a variable of a supertype can refer to a subtype object.
§
Polymorphism in OOP is the ability of an entity to take several forms.
§
Polymorphism literally means “being able to assume different forms.”
§
Polymorphism is an important and powerful concept in OOP.
§
It is the ability to process objects in a hierarchy differently depending on their actual
class type.
157
Object Oriented Programming - By Haftom
Berhe
Polymorphism
§
Polymorphism just means that different objects can respond to the same message in
§
Polymorphism can work for both variables/states and methods/behaviors of objects.
§
However, two powerful polymorphic concepts are often useful when you define a
class:
(Types of Polymorphism-)
§
§
Compile-time and Run-time
method overloading and method overriding. or
Java implements polymorphism through method overloading and method overriding.
159
Object Oriented Programming - By Haftom
Berhe
Polymorphism
different ways.
§
158
Object Oriented Programming - By Haftom
Berhe
class Shapes {
public void area() {
System.out.println("The formula for area of ");
}
}
class Triangle extends Shapes {
public void area() {
System.out.println("Triangle is ½ * base * height ");
}
}
class Circle extends Shapes {
public void area() {
System.out.println("Circle is 3.14 * radius * radius ");
}
} 160
Object Oriented Programming - By Haftom
Berhe
Polymorphism
Typecasting in Java
§ Dynamic Binding
§
§
§
A method can be implemented in several classes along the inheritance chain.
The JVM decides which method is invoked at runtime.
A method can be defined in a superclass and overridden in its subclass.
§
One object reference can be typecast into another object reference. This is called casting object.
§
In the preceding section, the statement
m(new Student());
Object o = new GeometricObject();
§
System.out.println(o.toString());
§
§
assigns the object new Student() to a parameter of the Object type.
This statement is equivalent to
Upcasting takes place when the Parent class’s reference variable refers to the object of the child
class. For example:
class A{}
class B extends A{}
A a=new B(); //upcasting
Object o = new Student(); // Implicit casting
m(o);
§
The statement Object o = new Student(), known as implicit casting, is legal because an instance of
Student is an instance of Object.
161
Object Oriented Programming - By Haftom
Berhe
Typecasting in Java
162
Object Oriented Programming - By Haftom
Berhe
Abstract Classes
§
Student b = (Student)o; // Explicit casting
§
It is always possible to cast an instance of a subclass to a variable of a superclass (known as upcasting).
§
Type casting for primitive data type to another.
int age = 45;
// A new value is assigned to newAge
byte newAge = (byte)age;
§
An abstract class is a class that cannot be instantiated—we cannot create instances of an abstract
class.
§
However, casting an object reference does not create a new object.
§
For example
Object o = new Circle();
Circle c = (Circle)o; // No new object is created
163
Object Oriented Programming - By Haftom
Berhe
§
One or more methods may be declared, but not defined.
(The programmer has not yet written code for a few methods).
§
The declared methods and classes have the keyword abstract in their signature.
§
There are two types of classes Abstract class and Concrete class.
§
If abstract keyword is used before the class then it is an Abstract Class if nothing is written before
class then it is a Concrete class.
§
164
Reference of abstract class is allowed.
Object Oriented Programming - By Haftom
Berhe
Abstract Classes
Example
§ Ways to achieve Abstraction in Java
§
§
§
The process of Abstraction in Java can be achieved by the following two methods as mentioned
below:
§ Implementing an Abstract Class
§ Implementing an Interface
The Syntax for Abstract Classes
//a super abstract class
abtract class Super {
abstract void method();
}
Abstract class may
have also
non-abstract method
which has a body
§
§
Object of an Abstract
class cannot be
created but object of
Concrete class can be
created.
Reference of abstract
class is allowed.
Example:
//a super abstract class
abstract class Super {
Super() {
System.out.println(“Super”);
}
void meth1() {
System.out.println(“meth1”);
}
abstract void meeth2();
}
abstract class and
abstract method
//concrete class
§
§
Abstract class can include Abstract and Non-Abstract methods in them.
They can include constructors and static methods.
class sub extends Super {
Void meth2() {
System.out.println(“meth2”);
}
165
Object Oriented Programming - By Haftom
Berhe
Cont.…
166
Object Oriented Programming - By Haftom
Berhe
Abstract Classes
class test {
§
public static void main() {
If any other class inherits abstract class then that class also becomes abstract class but to become a
concrete class the subclass must override the undefined method.
Super s1; // reference of abstract is allowed
§
A class becomes useful if it overrides all the methods of abstract class
§
Abstract classes are used for imposing standards and sharing methods
§
Sub classes are meant for following standards.
sub s2 =new sub();
}
}
§
Object of an Abstract class cannot be created but object of Concrete class can be created.
§
Reference of abstract class is allowed.
§
Example: Method which is not having a body is known as Abstract method, the method must be
declared as abstract.
§
The abstract method is undefined method. A class is Abstract class if at least one of the methods
is abstract.
167
}
Object Oriented Programming - By Haftom
Berhe
168
Object Oriented Programming - By Haftom
Berhe
Abstract Classes
Interfaces
§ Do’s and Don’ts of Abstract Class
§
§
§
§
An Abstract class cannot be final because if it is made final then it cannot be extended whereas
abstract class is meant for inheritance.
An Abstract method cannot be final because if it made final then it cannot be overridden whereas
Abstract method is meant for overriding.
Abstract Class and method can neither be final nor static.
A Sub class must override an abstract method or else it will become abstract class.
§
Inheritance is used for borrowing methods.
§
Abstract is used for achieving polymorphism as well as Inheritance.
§
Inheritance is completely used for achieving Polymorphism.
§
Interface can be call as Abstract Class with all abstract methods.
§
All the methods are by default abstract.
§
Classes are extended but Interfaces are implemented.
§
In Interface we can have reference of interface and the object of the class which is
implemented.
169
Object Oriented Programming - By Haftom
Berhe
Interfaces
§
170
Object Oriented Programming - By Haftom
Berhe
Interfaces
In java a class can extend from one class only but if a class is implementing an interface then it can
Example Program
Interface
interface test1 {
void meth2();
§
An interface in Java is a collection of abstract methods and static constants.
}
§
As you might know in an interface, each method is public and abstract but it does not contain any
class test2 implements test1 {
public void meth2() {}
Along with abstraction, the interface also helps to achieve multiple inheritance in Java.
§
Implementation of
abstract method in
derived class
public void meth1() {}
constructor.
§
Collection of abstract
method
void meth1();
implement from multiple interfaces.
}
class test {
Note: You can achieve 100% abstraction using interfaces.
public static void main(String[] args){
test1 t=new test2 ();
t. meth1();
Calling method
} }
171
Object Oriented Programming - By Haftom
Berhe
172
Object Oriented Programming - By Haftom
Berhe
Creating an object derived
class
Interfaces
Interfaces
§ Do’s and Don’ts of Interfaces
§ By default, methods are Public and Abstract.
§ As methods are to be implemented by the classes, they can’t be made
private.
§ Identifiers can be used in interfaces but the identifiers must be given
in Upper cases.
§ Identifiers are by default final and static.
§ Method inside an interface cannot have body but the method can
have body if the method is static.
§ Static members can be accessed in main method by using interface
name and dot operator.
173
Object Oriented Programming - By Haftom
Berhe
174
Object Oriented Programming - By Haftom
Berhe
Abstraction vs Encapsulation
Interface vs Abstract Class
Interface.
Abstract Class
§ Can have only Abstract Methods
§ Can have Abstract and Non-Abstract
Methods
§ It has only Final Variables
§ It includes Non-Final Variables
§ It has Static and Final variables only
§ It has Static, Non-Static, final, Non-Final
variables
§ Will not implement the Abstract Class
§ Can implement an Interface
§ Implemented using “implements”
Keyword
§ Implemented using “extends” Keyword
§ Can extend only an Interface
§ Can extend Java Classes and Interfaces
§ Members are Public by default
§ Members can be Private and Protected
175
§ Do’s and Don’ts of Interfaces
§ An interface can be extended from another interface.
§ Interface VS Multiple Inheritance
§ In C++ one class can inherit from multiple classes.
§ Multiple Inheritance in java is achieved using Interfaces.
§ Interfaces are perfect than using Multiple Inheritance.
§ Way of thinking in java is more perfect than C++.
Object Oriented Programming - By Haftom
Berhe
Abstraction.
Encapsulation
§ Solves the problem in design level
§ Solves the problem in the implementation
level
§ Used for hiding unwanted data and giving
relevant results.
§ Outer layout – used in terms of design
176
§ Encapsulation means hiding the code and data
into a single unit to protect data from the
outside world
§ Inner layout – used in terms of
implementation
Object Oriented Programming - By Haftom
Berhe
Chapter Outlines
Exceptions Overview
Catching Exceptions
The finally Block
Exception Methods
Declaring Exceptions
Defining and Throwing Exceptions
Errors and Runtime Exceptions
§
§
§
§
CHAPTER FOUR
§
§
Exception Handing
177
Object Oriented Programming - By Haftom Berhe
Introduction
§
§
178
Introduction
Exception handling enables a program to deal with exceptional situations and continue its normal
§
execution.
§
Examples of exception:
§
Two cases exist when you design & code a program.
–
The case where nothing unusual happens and
–
The case where exceptional things happen.
§
An exception is an object that represents an error or a condition that prevents execution from
proceeding normally.
§
If the exception is not handled, the program will terminate abnormally.
§
How can you handle the exception so that the program can continue to run or else terminate
gracefully?
§
Object Oriented Programming - CoSc2051
E.g., Array out of bounds, Division by zero, etc.
Exception handling enables programmers to create applications that
can resolve exceptions.
§
Exception-Handling Overview:
Exceptions are thrown from a method.
§ The caller of the method can catch and handle the exception.
Look below example which reads in two integers and displays their
quotient.
§
§
179
Object Oriented Programming - CoSc2051
180
Object Oriented Programming - CoSc2051
What are Exceptions?
§
Exceptions are Runtime Errors.
§
There are various types of errors
§
§
§
181
§
183
Syntax Error
§ Syntax and Logical errors are faced by Programmers, and
runtime errors are faced by user.
§ Spelling or grammatical mistakes are syntax errors:
§ For example using uninitialized variable it and using undefined
variable etc and missing a semicolon etc.
§ Syntax errors can be removed with the help of compiler.
§
Syntax Error
Logical Error
Runtime Error.
Object Oriented Programming - CoSc2051
What are Exceptions?
§
What are Exceptions?
Logical Error
§ Logical error is a bug in program that it to operate incorrectly, for example
missing parenthesis in the calculation.
§ Logical errors are removed with the help of debugger.
Runtime Error.
§ Mishandling of a program causes Runtime error.
§ Causes of runtime errors are bad input, unavailability of resources.
§ Major problems with runtime errors is program will crash.
§ Exception handling is process of responding to the runtime errors.
Object Oriented Programming - CoSc2051
182
Object Oriented Programming - CoSc2051
Introduction to Exception Example
public class Quotient {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Prompt the user to enter two integers
System.out.print("Enter two integers: ");
int number1 = input.nextInt();
int number2 = input.nextInt();
System.out.println(number1 + " / " + number2 + " is " + (number1 / number2));
}
}
184
Object Oriented Programming - CoSc2051
Java built Exception Classes
Object is the mother class for all the java classes.
§
Exception is the parent class for all the exceptions.
§
Java Built Exception Classes
Object
•
Throwable
•
Error
§
All exception classes are subtypes of the java.lang.Exception class.
§
The exception class is a subclass of the Throwable class.
•
Exceptions
These are not exceptions at all, but problems that arise beyond the
control of the user or the programmer.
Errors are typically ignored in your code because you can rarely do
anything about an error.
• For example, if a stack overflow occurs, an error will arise.
They are also ignored at the time of compilation.
ClassNotFoundException
IOException
Other than the exception class there is another subclass called Error
§
InterruptedException
which is derived from the Throwable class.
}
Errors are not normally trapped form the Java programs.
Checked Exception
NumberFormatException
RuntimeException
ArithmeticException
ArrayIndexOutOfBoundsException
NullPointerException
185
Object Oriented Programming - CoSc2051
Exception Types
RuntimeException, Error, and their subclasses are known as unchecked exceptions.
§
All other exceptions are known as checked exceptions.
§
Exceptions are objects.
§
Any class designed for throwable objects must extend the class Throwable or
one of its subclasses.
meaning that the compiler forces the programmer to check and deal with them
in a try-catch block or declare it in the method header
§
}
§
Checked Exceptions: the compiler checks that your methods throw only the
Exceptions can be of two types:
}
Checked Exceptions: the compiler checks that your methods throw only
the exceptions they have declared themselves to throw.
Unchecked Exceptions: conditions that reflect errors in your program's logic and
}
cannot be reasonably recovered from at run time.
Object Oriented Programming - CoSc2051
The Throwable class contains a string that can be used to describe the
exception.
exceptions they have declared themselves to throw.
187
§
Exceptions can be of two types:
}
Unchecked Exception
Object Oriented Programming - CoSc2051
Java Exception Hierarchy
§
§
186
Unchecked Exceptions: conditions that reflect errors in your program's
logic and cannot be reasonably recovered from at run time.
188
Object Oriented Programming - CoSc2051
Exception Types(1) - Checked Exceptions
Exception Types(2) - Unchecked Exceptions
§
§
All Java exception classes inherit directly or indirectly from Throwable.
§
An IOException is also known as a checked exception.
§
They are checked by the compiler at the compile-time and the programmer is
§
prompted to handle these exceptions.
§
§
§
189
Some of the examples of checked exceptions are:
§
Trying to open a file that doesn’t exist results in FileNotFoundException
§
Trying to read past the end of a file.
Object Oriented Programming - CoSc2051
Java’s Built-in (Unchecked Exception)
191
§
Object Oriented Programming - CoSc2051
Reflect errors in your program's logic.
A runtime exception happens due to a programming error.
They are also known as unchecked exceptions.
These exceptions are not checked at compile-time but run-time.
Some of the common runtime exceptions are:
§ Improper use of an API - IllegalArgumentException
§ Null pointer access (missing the initialization of a variable) NullPointerException
§ Out-of-bounds array access - ArrayIndexOutOfBoundsException
§ Dividing a number by 0 - ArithmeticException
190
Object Oriented Programming - CoSc2051
Java’s Built-in Exceptions(checked Exception)
§
The classes that inherit all the exceptions from the throwable parent class directly, but except for the
run-time exception, are called the checked exceptions.
§
A checked exception extends the Exception class.
192
Object Oriented Programming - CoSc2051
Checked vs Unchecked Exception
Checked Exception
.
Unchecked Exception
§ Can be checked and handled during
Compile-time
§ Cannot be checked nor be handled during Compiletime
§ Direct subclasses of exception class but do
not inherit run-time exception
§ Direct subclasses of exception class but only
inherits run-time exception
§ The compiler catches these exceptions in
the compilation stage
§ The compiler cannot recognize and catch them
during the compilation stage
§ Checked Exceptions are predictable
failures
§ Uncheck exceptions are unpredictable failures,
mostly caused by improper programming logic
§ Examples:
§ SQL Exception
§ IOException
§ Examples:
§ ArithmeticException
§ NullPointerException
193
In Java, there is a way to deal with cases where exceptional things can happen.
–
§
.
Object Oriented Programming - CoSc2051
Introduction to Exception Handling
§
Exceptions Methods
194
Basics of Java Exception Handling
}
A method detects an error and throws an exception
}
The way is known as exception handling.
–
Handles errors
§
Class Exception
195
}
Example: a method that handles division by zero.
§
Object Oriented Programming - CoSc2051
Exception handler processes the error
}
It deals with methods that have some special case that is handled differently
depending on how the method is used.
Object Oriented Programming - CoSc2051
The error is considered caught and handled in this model
Code that could generate errors put in try blocks
}
Code for error handling enclosed in a catch block
}
The finally always executes with or without an error
}
Keyword throws tells exceptions of a method
}
Termination model of exception handling
}
196
The block in which the exception
occursProgramming
expires- CoSc2051
Object Oriented
When Exception Handling Should Be Used
§
A method should throw an exception if the error needs to be handled by its caller.
§
Uses of exception handling
How to handle exceptions?
§
In Java, exception handling proceeds as follows:
Either some library software or your code provides a mechanism that signals when something
§
unusual happens.
–
When method cannot complete its task.
–
Process exceptions from program components.
–
Handle exceptions in a uniform manner in large projects.
–
Handle Invalid user input.
–
When possible Code errors.
–
Opening an unavailable file.
§
At another place in your program you place the code that deals with the exceptional case.
§
§
§
197
Object Oriented Programming - CoSc2051
try block….
This is called throwing an exception.
This is called handling the exception.
Here's a list of different approaches to handle exceptions in Java.
§
try...catch block
§
finally block
§
throw and throws keyword
198
Object Oriented Programming - CoSc2051
Recap
§
It “tries” to execute the case where all goes smoothly.
§
If something exceptional does happen, you want to throw an exception.
§
Indicates that something unusual happened.
§
The basic outline, when we add a throw, is as follows:
1.
What is the output of the following code?
public class Test {
public static void main(String[] args) {
try {
int value = 30;
if (value < 40)
throw new Exception("value is too small");
}
catch (Exception ex) {
System.out.println(ex.getMessage());
}
System.out.println("Continue after the catch block");
}
}
What would be the output if the line
try {
// code
} catch(Exception e) {
// code
}
int value = 30;
were changed to
199
Object Oriented Programming - CoSc2051
200
int value = 50;
Object Oriented Programming - CoSc2051
try block….
catch block
.
Try … Catch Exception Example
public class TryCatchException {
§
§
public static void main(String[] args) {
try {
// code that generate exception
int divideByZero = 5 / 0;
System.out.println("Rest of code in try block");
}
catch (ArithmeticException e) {
System.out.println("ArithmeticException => " +
e.getMessage());
}
}
}
201
Object Oriented Programming - CoSc2051
catch block
§
When an exception is thrown, it can be caught and handled in a try-catch block, as
follows:
If no exceptions arise during the execution of the try block, the catch blocks are
skipped.
203
§
§
§
§
202
Object Oriented Programming - CoSc2051
Example 1
try {
statements; // Statements that may throw exceptions
}
catch (Exception1 exVar1) {
handler for exception1;
}
...
catch (ExceptionN exVarN) {
handler for exceptionN;
}
§
§
A catch block begins execution when an exception is thrown in the try block.
The catch block has a parameter.
Exception object thrown is plugged in for this catch block parameter.
Executing of the catch block is called catching the exception or handling the
exception.
When an exception is thrown, it should ultimately be handled by (caught by) some
catch block.
Catch block immediately follows the try block.
The catch block catches the exception and statements inside the catch block is
executed.
Object Oriented Programming - CoSc2051
class Division {
public static void main(String[] args {
int a, b, result;
Scanner input = new Scanner(System.in);
System.out.println("Input two integers");
a = input.nextInt();
b = input.nextInt();
// try block
try {
result = a / b;
System.out.println("Result = " + result);
}
// catch block
catch (ArithmeticException e) {
System.out.println("Exception caught: Division by zero.");
}
}
}
204
Object Oriented Programming - CoSc2051
Java throw and throws keyword
Example 2
Output of the program.
class Exceptions {
public static void main(String[] args) {
C++
String languages[] = { "C", "C++", "Java", "Perl",
"Python" };
Java
try {
Python
Perl
for (int c = 1; c <= 5; c++) {
java.lang.ArrayIndexOutOfBoundsException: 5
System.out.println(languages[c]);
§
Java throw
The Java throw keyword is used to explicitly throw a single exception.
§ When we throw an exception, the flow of the program moves from the try block to
the catch block.
§ The “throw” keyword throws an exception.
§
public class ThrowException {
}// end of for loop
public static void divideByZero() {
}
// throw an exception
catch (Exception e) {
System.out.println(e);
throw new ArithmeticException("Trying to divide by 0");
}
}
}
public static void main(String[] args) {
}
divideByZero();
205
Object Oriented Programming - CoSc2051
}
206
Object Oriented Programming - CoSc2051
}
Declaring exceptions
§
Declaring exceptions…
Java throws
§ Similarly, the throws keyword is used to declare the type of exceptions that might
occur within the method.
§ The “throws” keyword is used to declare an exception.
§ Its syntax is:
§
throws Example
public class ThrowsException {
public static void findFile() throws IOException {
// code that may produce IOException
File newFile=new File("test.txt");
FileInputStream stream=new FileInputStream(newFile);
}
accessModifier returnType methodName() throws
ExceptionType1,
public static void main(String[] args) {
try {
findFile();
}
catch (IOException e) {
System.out.println(e);
}
}
}
ExceptionType2 … {
// code
}
§
§
207
Including an exception class in a throws clause is called declaring the exception.
Example
public void sampleMethod() throws DivisionByZeroException
Object Oriented Programming - CoSc2051
208
java.io.FileNotFoundException
: test.txt (No such file or
directory)
Object Oriented Programming - CoSc2051
Declaring exceptions…
Recap throws Example
§
§
§
When we run this program, if the file test.txt does not exist,
FileInputStream throws a FileNotFoundException which
extends the IOException class.
If a method does not handle exceptions, the type of exceptions that
may occur within it must be specified in the throws clause so that
methods further up in the call stack can handle them or specify them
using throws keyword themselves.
The findFile() method specifies that an IOException can be
thrown.
§ The main() method calls this method and handles the exception if it
is thrown.
209
If there is more than one possible exception that can be thrown in the method definition, then the
exception types are separated by commas.
public void sampleMethod() throws DivisionByZeroException,
SomeOtherException
}
}
To declare an exception in a method, use the throws keyword in the method header, as in this
example:
}
Your method definition must include a catch block that will catch the exception or
}
You must declare (that is, list) the exception class within a throws clause.
210
The throws keyword indicates that myMethod might throw an IOException.
§
If the method might throw multiple exceptions, add a list of the exceptions, separated by commas, after
throws:
}
}
public void myMethod() throws Exception1, Exception2,
..., ExceptionN
211
Object Oriented Programming - CoSc2051
Object Oriented Programming - CoSc2051
Catch or Declare Rule
public void myMethod() throws IOException
§
This technique is a form of shifting responsibility (“passing the buck”).
If you define a method that might throw exceptions of some particular class, then normally either
Object Oriented Programming - CoSc2051
Declaring exceptions…
§
}
}
Most “ordinary” exceptions that might be thrown when a method is
invoked must be accounted for in one of two ways:
} The possible exception can be caught in a catch block within the
method definition.
} The possible exception can be declared at the start of the method
definition by placing the exception class name in a throws clause.
This is known as the Catch or Declare Rule.
In any one method, you can mix the two, catching some exceptions and
declaring others in a throws clause.
212
Object Oriented Programming - CoSc2051
The finally Block
The finally Block
}
The finally block contains code to be executed whether or not an exception is thrown in a
try block.
}
The finally block, if used, is placed after a try block and its following catch blocks. The general syntax
is as follows:
try {
//some code here
}catch(Exception e){
System.out.println("Trying to divide by 0 "+ e);
}
finally{
System.out.println("Don't worry I always excuted ");
}
}
}
There is 3 possibilities when the code in the try-catch-finally blocks is run:
1. The try block runs to the end and no exception is thrown.
} In this case, the finally block is executed after the try block.
2. An exception is thrown in the try block and is caught in one of
the catch blocks positioned after the try block.
} In this case, the finally block is executed after the catch block is executed.
3. An exception is thrown in the try block and there is no
matching catch block in the method to catch the exception.
} In this case, the method invocation ends and the exception object is thrown to the
enclosing method.
} However, the finally block is executed before the method ends.
}
213
Object Oriented Programming - CoSc2051
214
Object Oriented Programming - CoSc2051
The finally Block Example
class Allocate {
.
public static void main(String[] args){
try {
long data[] = new long[1000000000];
} catch (Exception e) {
Chapter 5
System.out.println(e);
} finally {
System.out.println("finally block will execute always.");
Packages
}
} }
215
Output of program:
finally block will execute always.
Exception in thread "main" java.lang.OutOfMemoryError: Java heap
space at Allocate.main(Allocate.java:5)
Object Oriented Programming - CoSc2051
216
Object Oriented Programming - By Haftom Berhe
Download