0% found this document useful (0 votes)
13 views274 pages

OOP ch1

Uploaded by

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

OOP ch1

Uploaded by

the bekalus
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 274

Object-Oriented Programming

with Java
Information technology Year II

1
Chapter One

Introduction to Object –Oriented


Programming

2
Overview of OOP?
Programming Paradigms
 A programming paradigm is a fundamental style of
computer programming, a way of building the structure and
elements of computer programs.
Two paradigms of programming approach:
1.“What is happening?”(process oriented approach i.e.
Procedural approach )
 a programmer specifies a set of instructions to perform
a specific task in the form of procedures or functions.
• C, Fortran etc.
Cont…
 Data centric,
 Become unmanageable when logic becomes
complex
 No reuse functionality
2. “Who is being affected?”(object oriented approach )
 Object-Oriented Programming is a methodology
or paradigm to design a program using classes
and objects. It simplifies the software development
and maintenance by providing some concepts:
Like Object,Class,Inheritance…
Cont…
 object oriented paradigm came into consideration to
reuse structures and functions and perform complex
task with the help of abstraction.
• C++, Java
Procedural vs. Object-Oriented Programming
 The unit in procedural programming is function, and unit in
object-oriented programming is class
 Procedural programming concentrates on creating functions,
while object-oriented programming starts from isolating the
classes, and then look for the methods inside them.
Origins of Java
 Java - The new programming language developed by Sun
Microsystems in 1991.
 Originally called Oak by James Gosling, one of the
inventors of the Java Language. but was renamed “Java”
in 1995.
 Originally created for consumer electronics (TV, VCR,
Freeze, Washing Machine, Mobile Phone).
 Java evolved from C++, which evolved from C, which
evolved from BCPL and B.
 Java is directly related to both C and C++. Java inherits its syntax
from C. Its object model is adapted from C++.
6
Continued…

• Originally Java was not designed for developing Internet-based


applications rather the need for a platform-independent
language used to create software to be embedded in various
consumer electronic devices(microwave ovens, remote controls).
• Java has become now the language of choice for implementing
Internet-based applications and software for devices that
communicate over a network.
• Java Enterprise Edition (Java EE) is geared toward developing
large-scale, distributed networking applications and web-based
applications.

7
Continued…
• Java Micro Edition (Java ME) is geared toward
developing applications for small, memory-
constrained devices, such as cell phones, pagers and
PDAs..
• Java is used to develop large-scale enterprise
applications, to enhance the functionality of web
servers, to provide applications for consumer devices.
• Java programs consist of pieces called classes. Classes
include pieces called methods that perform tasks and
return information when the tasks are completed.
8
Types of Languages
• Programming languages are divided into three general
types:
1. Machine language
2. Assembly language
3. High-level language
1. Machine Languages : is the “natural language” of a computer
which is defined by its hardware design.
Uses 0’s and 1’s to represent data inside computer system.

9
Continued…
2. Assembly Languages: Uses symbolic instructions
and executable machine codes called mnemonics to
write programs.
E.g. To add any two numbers A and B
ADD A, B – Adds two numbers in memory
location A and B
• A translator that converts Assembly language in
to Machine code is called Assembler.
10
Continued…

3. High-level Languages : Uses English like


statements to write programs.
E.g. To add any two numbers A and B
sum = A + B
• A translator that converts High level language in
to Machine code is called Compiler.
[FORTRAN, BASIC,C++,Java]
11
What is OOP?
• OBJECT-ORIENTATION is a set of tools and methods that
enable software engineers to build reliable, user friendly,
maintainable, well documented, reusable software systems
that fulfils the requirements of its users.
• An object-oriented programming language provides
support for the following object oriented concepts:
1. Objects and Classes
2. Inheritance
3. Polymorphism and Dynamic binding
12
Overview of OO Principles

• To support the principles of object-oriented programming, all


OOP languages, including Java, have three traits in common:
encapsulation, polymorphism, and inheritance.

1. Encapsulation
• Encapsulation is a programming mechanism that binds
together code and the data it manipulates, and that keeps
both safe from outside interference and misuse.
• used to hide unimportant implementation details from other
objects.
• Users can access the data, but not directly
13
and without having to have
direct knowledge of its structure.
Continued…

2. Polymorphism [Take many forms]


• Polymorphism is the quality that allows one interface to access a
general class of actions.
• It is a feature of object-oriented languages whereby the same
method call can lead to different behaviors depending on the type of
object on which the method call is made.
• It’s the ability to create variables and methods that has more than
one form.

3. Inheritance
• Inheritance is the process by which one object can acquire the
properties of another object.
• It is the mechanism whereby a class acquires
14 (inherits) the methods
and variables of its super classes.
Features of Java Language
• Simple: According to Sun, Java language is simple
because: syntax is based on C++ (so easier for
programmers to learn it after C++).
• Secure: Java is secured because Programs run
inside virtual machine sandbox.
• Portable: Java programs can execute in any
environment for which there is a Java run-time
system. [write once and run anywhere].
15
Continued…

• Robust: Java encourages error-free programming


by being strictly typed and performing run-time
checks. [ Avoid crashes during program execution]
• Multithreaded: Java provides integrated support
for multithreaded programming(Perform
concurrent computations).
• Architecture-neutral: Java is not tied to a specific
machine or operating system architecture
(Platform independent).
16
Continued…
• Object-Oriented: Java is pure OOP language -Object-
oriented means we organize our software as a
combination of different types of objects that
incorporates both data and behaviour.
• High performance: The Java bytecode is highly
optimized for speed of execution.
• Distributed: We can create distributed applications in
java. RMI and EJB are used for creating distributed
applications. We may access files by calling the
methods from any machine on the internet.
17
Java Applets and Applications

• An application is a program that runs on your


computer, under the operating system of that computer.
• An applet is an application designed to be transmitted
over the Internet and executed by a Java-compatible
Web browser.
• What makes Java different from other computer
languages is its ability to create applets.

18
Key Terms
• Objects are instances of a class.
• An object is a software bundle of related state(represented by its
attribute) and behaviour(method). Software objects are used to model
the real-world objects that you find in everyday life.
• Objects interact with each other by passing messages.
• Example.
• Bank Account
• Attributes: account number, owner, balance
• Behaviors: withdraw, deposit
• Dog
– Attributes: breed, color, hungry, tired, etc.
– Behaviors: eating, sleeping, etc.
19
Continued…
In object-oriented languages,
they are defined together.
– An object is a collection of Account
attributes and the Account
behaviors that operate on
Account
them.
number:
Variables in an object are
balance:
called attributes.
deposit()
Procedures associated with an
withdraw()
object are called methods.
Continued…

• A Class is a blueprint that defines the states and


the behaviors common to all objects of a certain
kind.
• A class is a collection of data and methods that
operate on that data.
• A method is the object-oriented term for a
procedure or a function.

21
Continued…
• An interface is a contract between a class and the
outside world.
• methods in interfaces do not have body.
• the variables declared in an interface are public,
static & final by default.
• A package is a namespace for organizing classes
and interfaces in a logical manner. Placing your
code into packages makes large software projects
easier to manage.
22
Typical Java Development Environment

23

24
The JVM and Byte Code
 Java Development Kit (JDK): Java Development
Kit contains two parts. One part contains the
utilities like javac, debugger, jar which helps in
compiling the source code (.java files) into byte
code (.class files) and debug the programs. The
other part is the JRE, which contains the utilities
like java which help in running/executing the
byte code. If we want to write programs and run
them, then we need the JDK installed.
Java Run-time Environment (JRE):
• Java Run-time Environment (JRE): Java Run-
time Environment helps in running the
programs. JRE contains the JVM, the java
classes/packages and the run-time libraries. If
we do not want to write programs, but only
execute the programs written by others,
then JRE alone will be sufficient.
Java Virtual Machine (JVM):
• Java Virtual Machine (JVM): Java Virtual
Machine is important part of the JRE,
which actually runs the programs
(.classfiles), it uses the java class
libraries and the run-time libraries to
execute those programs. Every
operating system(OS) or platform will
have a different JVM.
Continue…

• Just In Time Compiler (JIT): JIT is a module inside


the JVM which helps in compiling certain parts of
byte code into the machine code for higher
performance. Note that only certain parts of byte
code will be compiled to the machine code, the
other parts are usually interpreted and executed.
• Java is distributed in two packages - JDK and JRE.
When JDK is installed it also contains
the JRE, JVM and JIT apart from the compiler,
debugging tools. When JRE is installed it contains
the JVM and JIT and the class libraries.
The End of Chapter One
ou
k y
a n
T h
Question???
29
2016

Object-Oriented Programming
with Java
Information Technology Year II
Compiled by: Birhan H.

30
Chapter Two

Overview of Java Principles

31
2. Basics of Java Programming
2.1 Structure of Java Program
[Comments]
[Namespaces]
[Classes]
[Objects]
[Variables]
[Methods]

32
2.3 My First Java Program

import java.io.*; //Java class for I/O


public class Hello { //Java class called Hello
// My first java program
public static void main(String[] args) { //Java main function
//prints the string "Hello world" on screen
System.out.println("Hello world!"); /*Prints Hello world to the console on new line */
}}
• The "public static void" key words in the main function has the following meanings
• public – specifies that the method is accessible to all other classes and to the interpreter
• static – this keyword specifies that the method is one that is associated with the entire
class,
• It is not associated with objects belonging to the class
• void – specifies that the method does not return any value.

33
2.4 Basic Elements of Java
• The basic elements of Java are:
1. Keywords (Reserved Words)
2. Identifiers
3. Literals
4.Comments

34
2.4.1 Java Keywords/Reserved Words
• Keywords are predefined identifiers reserved by Java for a specific purpose.
• There are 48 reserved keywords currently defined in the Java language. These keywords cannot be used
as names for a variable, class or method [Identifiers].
• The keywords const and goto are reserved but not used.

35
Continued…

Keyword Purpose
boolean declares a boolean variable or return type [True/False - 0/1]
byte declares a byte variable or return type
char declares a character variable or return type [Single character]
double declares a double variable or return type
float declares a floating point variable or return type
short declares a short integer variable or return type
void declare that a method does not return a value
int declares an integer variable or return type
long declares a long integer variable or return type
while begins a while loop
for begins a for loop
do begins a do while loop
switch tests for the truth of various possible cases
break prematurely exits a loop
continue prematurely return to the beginning of a loop
case one case in a switch statement 36

default default action for a switch statement


Continued…
if execute statements if the condition is true
else signals the code to be executed if an if statement is not true
try attempt an operation that may throw an exception
catch handle an exception
finally declares a block of code guaranteed to be executed
class signals the beginning of a class definition
abstract declares that a class or method is abstract
extends specifies the class which this class is a subclass of
declares that a class may not be subclassed or that a field or method may not
final
be overridden
implements declares that this class implements the given interface
import permit access to a class or group of classes in a package
instanceof tests whether an object is an instanceof a class
interface signals the beginning of an interface definition
native declares that a method is implemented in native code
new allocates a new object
package defines the package in which this source code file belongs
37
private declares a method or member variable to be private
Continued…
protected declares a class, method or member variable to be protected

public declares a class, method or member variable to be public


return returns a value from a method

static declares that a field or a method belongs to a class rather than an object

super a reference to the parent of the current object

synchronized Indicates that a section of code is not thread-safe

this a reference to the current object


throw throw an exception

throws declares the exceptions thrown by a method

transient This field should not be serialized

volatile Warns the compiler that a variable changes asynchronously

38
2.4.2 Java Identifiers
• Identifiers are tokens that represent names of variables,
methods, classes, packages and interfaces etc.
• Rules for Java identifiers.
• Begins with a letter, an underscore “_”, or a dollar sign
“$”.
• Consist only of letters, the digits 0-9, or the underscore
symbol “_”
• Cannot use Java keywords/reserved words like class,
public, private, void, int float, double…
• Cannot use white spaces
39
2.4.3 Java Literals
• Literals are tokens that do not change or are constant. The different
types of literals in Java are:
• Integer Literals: decimal (base 10), hexadecimal (base 16), and octal
(base 8).Example: int x=5; //decimal
int x=0127; //octal
int x=0x3A; //hexadecimal or int x=OX5A;

• Floating-Point Literals: represent decimals with fractional parts.


Example: float x=3.1415;
• Boolean Literals: have only two values, true or false (0/1).
Example: boolean test=true;
• Character Literals: represent single Unicode characters. A Unicode
character is a 16-bit character set that replaces the 8-bit ASCII
character set. Example: char ch=‘A’;
• String Literals: represent multiple/sequence
40
of characters enclosed
2.4.4 Java Comments

 Comments are notes written to a code for documentation purposes.


Those text are not part of the program and compiler ignores executing
them. They add clarity and code understandability.
 Java supports three types of comments:
1. C++-Style/Single Line Comments – Starts with //
• Everything on a single line after // is ignored by the compiler.
E.g. // This is a C++ style or single line comments
2. C-Style: Multiline comments – Starts with /* and ends with */
• Everything between /* and */ is ignored by the compiler.
E.g. /* This is an example of a
C-style or multiline comments */
3. Documentation Comments: is used to produce an HTML file that documents
your program. The documentation comment begins with a /** and ends with a */.
41
E.g. /** This is documentation comment */.
2.5 Data Types, Variables, and Constants
2.5.1 Variables
• A variable is an item of data used to store state of objects.
• A variable has a data type and a name. The data type indicates the type of value that the
variable can hold. The variable name must follow rules for identifiers.
• Declaring Variables
To declare a variable is as follows,
General syntax:-
datatype name;
int x;
• Initializing Variables [At moment of variable declaration]
int x = 5; // declaring AND assigning
char ch = ‘A’; //initializing character
• Assigning values to Variables [After variable declaration]
int x; // declaring a variable
x = 5; // assigning a value to a variable

42
2.5.2 Basic 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)
• 1 Boolean (boolean)
• 1 Character (char)

43
Summary of Java Primitive Data Types

Data Type Size Range


boolean 1 byte Take the values true and false only (0/1).

byte 1 byte -27 to 27 -1

short 2 bytes -215 to 215-1


int 4 bytes -231 to 231-1
long 8 bytes -263 to 263-1

float 4 bytes -231 to 231-1

double 4 bytes -263 to 263-1


char 8 bytes 256 characters (Stores single character): ‘x’
String 1 byte Sequence of characters :“Hello world”

44
2.5.3 Constants
• Constants
In Java, a variable declaration can begin with the final keyword. This means that once an initial
value is specified for the variable, that value is never allowed to change.
Example: final float pi=3.14; //const pi-3.14 in c++
final int max=100; //or
final int max;
max=100;
public class Area_Circle {
public static void main(String args[]) {
final double pi=3.14;
double area=0; //initialize area to 0
double rad=5;
area=pi*rad*rad; //computer area
System.out.println("The Area of the Circle: "+area);}
}
45
2.6 Java Operators
• An operator is a symbol that operates on one or more arguments to
produce a result.
2.6.1 Assignment Operator (=)
• The assignment operator is used for storing a value at some memory
location (typically denoted by a variable).
• Var=5 assigning a value to a variable using =.

Operator Example Equivalent To


= n = 25
+= n += 25 n = n + 25
-= n -= 25 n = n - 25
*= n *= 25 n = n * 25
/= n /= 25 n = n / 25
%= n %= 25 n = n % 25
46
Illustration of assignment operators
class Assign {
public static void main( String args[] ) {
int a=1;
int b=2;
int c=3;
a+=5;
b*=4;
c+=a*b;
c%=6; Output
System.out.println("a="+ a); a=6
System.out.println("b="+ b); b=8
System.out.println("c="+ c); c=3
}
}

47
2.6.2 Arithmetic Operators

• Java has five basic arithmetic operators. ( +, -, *, /, %)

Operator Name Use Description

+ Addition op1 + op2 Adds op1 and op2

- Subtraction op1 - op2 Subtracts op2 from op1

* Multiplication op1 * op2 Multiplies op1 by op2

/ Division op1 / op2 Divides op1 by op2

% Remainder op1 % op2 Computes the remainder of dividing op1 by op2

48
Illustration of arithmetic operators.

• Open a new file in the editor and type the following script.
class ArithmeticOperators {
public static void main(String args[]) {
int x=10; output
int y=20;
int z=25; The value of x+y is 30
The value of z-y is 5
System.out.println( "The value of x+y is " + (x+y)); The value of x*y is 200
System.out.println( "The value of z-y is " + (z-y)); The value of z/y is 0
The value of z%y is 5
System.out.println( "The value of x*y is " + (x*y));
System.out.println( "The value of z/y is " + (x/y));
System.out.println( "The value of z%y is "+ (z%x));
}
}
49
2.6.3 Relational Operators
Java has six relational/comparison operators that compare two numbers and return a
boolean value. The relational operators are <, >, <=, >=, ==, and !=.

Operator Name Description

x<y Less than True if x is less than y, otherwise false.

x>y Greater than True if x is greater than y, otherwise false.

x <= y Less than or equal to True if x is less than or equal to y, otherwise false.

x >= y Greater than or equal to True if x is greater than or equal to y, otherwise false.

x == y Equal True if x equals y, otherwise false.

x != y Not Equal True if x is not equal to y, otherwise false.

50
Illustration of relational operators.

class RelationalOperators {
public static void main(String args[]) {
int x=10;
int y=20;
System.out.println( "Demonstration of Relational Operators in Java");
if(x<y) {
System.out.println( "The value of x is less than y ");
}
else if(x>y) {
System.out.println( "The value of x is greater than y ");
}
else if(x==y) {
System.out.println( "The value of x is equal to y");
} output
else {
System.out.println( ""); Demonstration of Relational Operators in Java
}}} The value of x is less than y

51
2.6.4 Logical Operators
• Java provides three logical/conditional operators for combining logical expressions. Logical
operators evaluate to True or False.

Operator Name Example


! Logical Negation (NOT) !(5 == 5) // gives False
&& Logical AND 5 < 6 && 6 < 6 // gives False

|| Logical OR 5 < 6 || 6 < 5 //gives True

public class LogicalOps {


public static void main(String[] args) {
false
int x=6; output
false
int y=6; true
int z=5;
System.out.println(!(x==y)); //Prints False b/c true condition reversed by negating
System.out.println(z < 10 && y <5); //Prints False b/c Both conditions are not true
System.out.println(z < 6 | x > 7); //Prints True b/c one of the condition is True
}
52
}
Illustration of logical operators
import java.util.Scanner; //import statement for accepting input from keyboard
public class LogOps {
public static void main(String[] args) {
double mark;
Scanner input = new Scanner( System.in ); //Create Scanner to obtain input from command
//window
System.out.println( "Enter Student Mark: "); // prompt user to enter mark
mark = input.nextDouble(); // obtain user input from keyboard
if(mark<0 | mark>100) {
System.out.println("Invalid Input! Mark Must be between 0 & 100");
}
else if(mark>80 && mark<=100) {
System.out.println("A");
}
else if(mark>=60 && mark<80) { sample output
Enter Student Mark:
System.out.println("B") ; 60
} else { B
System.out.println("F");
} }} 53
2.6.5 Increment & Decrement Operators

Operator Use Description


++ x++ Increments x by 1; evaluates to the value of x before it was incremented

++ ++x Increments x by 1; evaluates to the value of x after it was incremented

-- x-- Decrements x by 1; evaluates to the value of x before it was decremented

-- --x Decrements x by 1; evaluates to the value of x after it was decremented

• Example Let x=5

Operator Name Example


++ Auto Increment (prefix) ++x + 10 // gives 16
++ Auto Increment (postfix) x++ + 10 // gives 15
-- Auto Decrement (prefix) --x + 10 // gives 14
-- Auto Decrement (postfix) x-- + 10 // gives 15
54
Illustration of increment & decrement operators
public class IncDec {
public static void main(String[] args) {
// Prefix increment and postfix increment operators.
int c;
c = 5; // assign 5 to c
//Pre incrementing and post incrementing.
System.out.println(c++ ); // prints 5 then post increments
c = 5; // assign 5 to c
System.out.println(++c ); // pre increments then prints 6
//Pre decrementing and post decrementing. output
c = 5;// assign 5 to c
System.out.println(c-- ); // prints 5 then post decrements 5
6
c = 5; // assign 5 to c 5
System.out.println(--c ); // pre decrements then prints 4 4
} // end main
} // end class IncDec 55
2.6.6 The precedence of the Java operators

Highest
() []
++ -- !
* / %
+ -
> >= < <=
== !=
&&
Lowest ||
Example:
c=Math.sqrt((a*a)+(b*b));
if((mark<0) || (mark>100))
if((mark>80) && (mark<100))

56
2.6.7 Java Statements & Blocks
• A statement is one or more line of code terminated by semicolon (;).
Example: int x=5;
System.out.println(“Hello World”);
• A block is one or more statements bounded by an opening & closing curly braces that
groups the statements as one unit.
Example:
public static void main(String args[]) {
int x=5;
int y=10;
char ch=‘Z’;
System.out.println(“Hello ”);
System.out.println(“World”); //Java Block of Code
System.out.println(“x=”+x);
System.out.println(“y=”+y);
System.out.println(“ch=”+ch);
} 57
2.6.8 Simple Type Conversion/Casting
• Type casting enables you to convert the value of one data from one type to another type.
• E.g.
(int) 3.14; // converts 3.14 to an int to give 3
(long) 3.14; // converts 3.14 to a long to give 3
(double) 2; // converts 2 to a double to give 2.0
(char) 122; // converts 122 to a char whose code is 122 (z)
(short) 3.14; // gives 3 as a short
public class TypeCasting {
public static void main(String[] args) {
double x=3.14;
int ascii = 65;
System.out.println("Demonstration of Simple Type Casting");
System.out.println((int) x); //3
System.out.println((long) x); //3
System.out.println((double) x); //3.0 Demonstration of Simple Type Casting
System.out.println((short) x); //3 3
System.out.println((char) ascii); //A
3
3.14
}
3
}
A
58
2.6.9 I/O Statements of Java [Scanner & BufferReader]
//Input Statements(Use Scanner class found in import java.util.Scanner package)
import java.util.Scanner;
public class IO {
public static void main(String[] args) {
String name;
int x;
float y; //Variable declarations
double z;
Scanner input = new Scanner( System.in ); /*Create Scanner in main function to obtain input from
command window */
System.out.println("Enter Your Name: "); //prompt user to enter name
name= input.nextLine(); // Obtain user input(line of text/string) from keyboard
System.out.println("Enter x, y, z:"); //prompt user to enter values of x, y & z
x= input.nextInt(); // Obtain user integer input from keyboard
y= input.nextFloat(); // Obtain user float input from keyboard
z= input.nextDouble(); // Obtain user float input from keyboard
//Output Statements(Use the statement System.out.println() & System.out.println())
System.out.println("Your Name is: "+name);
System.out.println("The Value of x is: "+x);
System.out.println("The Value of y is: "+y);
System.out.println("The Value of z is: "+z); 59
}}
Continued…
//Input Statements(Use BufferReader class found in import import.java.io package)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class GetInputFromKeyboard {
public static void main( String[] args )throws IOException {
BufferedReader dataIn = new BufferedReader(new InputStreamReader( System.in) );
String name;
int age;
String str;
System.out.print("Please Enter Your Name:");
name=dataIn.readLine();
System.out.print("Please Enter Your Age:");
str=dataIn.readLine(); //to read an input data
age=Integer.parseInt(str); //convert the given string in to integer
//Output Statement (Using System.out.println())
System.out.println("Hello "+ name +"! Your age is: "+age);
}}
60
Illustration of Java I/O Statements
import java.util.Scanner;
public class JavaIO {
public static void main( String args[] ) { // main method begins program
execution
String studID;
double gpa;
Scanner input = new Scanner( System.in ); /*Create Scanner to obtain input
from command window */
System.out.println( "Enter Student ID: "); // prompt user to enter ID
studID=input.nextLine(); // obtain user input from keyboard
System.out.println( "Enter GPA: "); // prompt
gpa=input.nextDouble(); // obtain user input
System.out.println("Student ID: "+studID); // Displaying Student ID to Console Screen
System.out.println("Student GPA: "+gpa); // Displaying GPA to Console Screen
}
}
61
Illustration of System.out.println() & System.out.print()

Here's a sample program,


public class OutputVariable {
public static void main( String[] args ){
int value = 10;
char x; //To input character from key board ch= (char) System.in.read();
x = ‘A’;
System.out.println( value ); //Prints 10
System.out.println( “The value of x=“ + x ); //Prints The value of x= A
System.out.println( “Hello“ ); //Prints Hello on new line
System.out.print( “World”); //Adds No new line, prints World after Hello
}
}
System.out.println() vs. System.out.print()
System.out.println() – appends a newline at the end of the data to output.
System.out.print() – Doesn’t print on new line.

62
Demonstration of The 4 Arithmetic Operations in Java
import java.util.Scanner;
public class Arithmetic {
public static void main(String[] args) {
int x, y, sum, dif, pro, Quo;
Scanner input=new Scanner (System.in); //create scanner object input to get input from user
System.out.println("Enter any 2 integers:");
x=input.nextInt();
y=input.nextInt();
sum=x+y;
dif=x-y;
pro=x*y;
Quo=(int) ((double) x/y);
System.out.println("The Sum x+y= "+sum);
System.out.println("The Difference x-y= "+dif);
System.out.println("The Product x*y= "+pro);
System.out.println("The Quotient x/y= "+Quo);
} //end of main
} //end of class arithmetic

63
3. Overview of Java Statements
• A running program spends all of its time executing statements.
The order in which statements are executed is called flow control
or (control flow). Flow control in a program is sequential, from one
statement to the next, but may be diverted to other paths by
branch statements.
• Program Control Statements allow us to change the ordering
(sequence) of how the statements in our programs are executed.
 There are different forms of Java statements:
 Declaration statements are used for defining variables.
 Assignment statements are used for simple, algebraic
computations.
 Branching statements are used for specifying alternate paths of
execution, depending on the outcome of a logical condition.
 Loop statements are used for specifying 64
computations, which
need to be repeated until a certain logical condition is satisfied.
4 Decision/Conditional Statements
• Decision statements are Java statements that allows us to select and execute
specific blocks of code while skipping other sections.
4.1 The if statement
• The if-statement specifies that a statement (or block of code) will be
executed if and only if a certain boolean statement is true.
• General form: if(expression)
statements;
• The first expression is evaluated. If the outcome is true then statement is
executed. Otherwise, nothing happens.
• Example: When dividing two values, we may want to check that the
denominator is nonzero
if(y!=0)
div=x/y;
65
Continued

4.2. The if-else statement


• The if-else statement is used to execute a certain statement if a condition is true, and a
different statement if the condition is false.
• General form: if(expression)
statement1;
else
statement2;
• First expression is evaluated. If the outcome is true then statement1 is executed. Otherwise,
statement2 is executed.
• Example: if(score>=50) {
System.out.println("Congratulations! U Passed!”; ");
}
else {
System.out.println(”U Failed!”);
System.out.println(”U Must Take This Course Again!”);
}

66
4.2.1 The if-else-if statement

• The statement in the else-clause of an if-else block can be another if-else structures.
• This cascading of structures allows us to make more complex selections.
• Example:

if(score<0 && score>100) { if(CGPA<0 && CGPA>4) {


System.out.println(“ Score [0-100]”); System.out.println(“CGPA [0-4]”);
} }
if(score>=85 && score<=100) { if(CGPA>=3.5 && CGPA<=4) {
System.out.println(“ A Grade”); System.out.println(“ Excellent!”);
} }
else if(score>=75 && score<85 ){ else if(CGPA>=3.0 && CGPA<3.5){
System.out.println(“ B Grade”); System.out.println(“ Very Good!”);
}
}
else if(CGPA>=2.5 && CGPA<3.0 ) {
else if(score>=65 && score<75 ) {
System.out.println(“ Good!”);
System.out.println(“ C Grade”);
}
} else if(CGPA>=2.0 && CGPA<2.5 ) {
else if(score>=50 && score<65 ) { System.out.println(“Satisfactory!”);
System.out.println(“D Grade”); }
} else {
else { System.out.println(“Poor!”);
System.out.println(“F Grade”); } 67
}
4.3 The switch statement

• Another way to indicate a branch is through the switch keyword.


• The switch construct allows branching on multiple outcomes.
• Multiple-choice, provides a way of choosing between a set of alternatives.
• General form:
switch (expression) {
case: constant1:
statements;
...
case: constantn:
statements;
default:
statements;
}

• First expression (called the switch tag) is evaluated, and the outcome is compared to each of
the numeric constants (called case labels), in the order they appear, until a match is found.
68
The final default case is optional and is exercised if none of the earlier cases provide a match.
Illustration of switch statement
switch(op)
{

// The 4 basic arithmetic operators using switch case '+':


import java.io.*; System.out.println("Sum="+(a+b));
public class switch1 break;
{
case '-':
public static void main(String args[])throws IOException
{ System.out.println("Sub="+(a-b));
String s; break;
char op; case '*':
int a, b;
BufferedReader aa=new BufferedReader(new
System.out.println("Mul="+(a*b));
InputStreamReader(System.in)); break;
System.out.print("The First Number:=");
case '/':;
s=aa.readLine();//to read an input data;
a=Integer.parseInt(s);//convert the given string in to integer System.out.println(“Quo="+(a/b));
System.out.print("The Second Number:="); break;
s=aa.readLine();//to accept a string from the use default:
b=Integer.parseInt(s);
System.out.println("Invalid Operator");
System.out.print("An Operator:=");
op=(char)aa.read();//to accept a character from the user } } }
69
Repetition/Looping Statements
• Repetition statements are Java statements that allows us to execute specific
blocks of code a number of times. There are three types of repetition statements,
the while, do-while and for loops.
The while loop statement
• The while loop is a statement or block of statements that is repeated as long as
some condition is satisfied(holds true).
• General form: while(expression)
statements;
inc/dec;
• First expression (called the loop condition) is evaluated. If the outcome is nonzero then
statement (called the loop body) is executed and the whole process is repeated. Otherwise,
the loop is terminated.
• Example: Adding the first 10 natural numbers(1-10)
int i=1,sum=0;
while(i<=10)
sum+=i;
i++; 70
The do…while loop statement
• The do loop is similar to the while statement, except that its body is executed first
and then the loop condition is examined.
• The statements inside a do-while loop are executed several times as long as the
condition is satisfied.
• General form:
do
statement;
while (expression);
• First statement is executed and then expression is evaluated. If the outcome of the
latter is nonzero then the whole process is repeated. Otherwise, the loop is
terminated.
• Example: int x = 0; int n;
do { do {
System.out.println(x); System.out.println(“Enter n: ”);
x++; n=input.nextInt();
} System.out.println((n*n));
while (x<10); }
71 while (n!=0);
The for loop statement
• The for loop allows execution of the same code a number of times.
• General form: for(Initialization;LoopCondition;StepExpression)
statement;
• Initialization -initializes the loop variable.
• LoopCondition - compares the loop variable to some limit value.
• StepExpression - updates the loop variable.
• First Initialization is evaluated. Each time round the loop, LoopCondition is evaluated. If
the condition is true then statement is executed and StepExpression is evaluated.
Otherwise, the loop is terminated.
• Example: int i, sum=0; int i;
for (i = 1; i <= n; i++) { for( i = 0; i < 10; i++ ) {
sum += i; System.out.print(i)
} }
• Loops can be nested:
for (int i = 1; i <= 3; ++i)
for (int j = 1; j <= 3; ++j)
System.ou.println(“(”+i+”, ”+j+”)”);
72
Branching Statements

• Branching statements allows us to redirect the flow of program execution. Java


offers three branching statements: break, continue and return.
The continue statement
• The continue statement terminates the current iteration of a loop and instead
causes to jump/proceed to the next iteration of the loop.
• Example:
int i, sum=0;
for ( i = 1; i <= 10; i++ ) { // loop 10 times
if ( i%3 == 0) {// if remainder of i divided by 3 is 0
continue;
}
sum+=i;
System.out.println(i+ “ +“);
} // end for
System.out.print( “= “+ sum );
73
The break statement
• break causes immediate termination/exit from looping/repetition statements
entirely.
• Example:
public class Break {
public static void main(String[] args) {
int num;
num = 10;
//loop while i is less than 6
for(int i=num; i >=1; i--) {
if(i<6){
break; // terminate loop if i <6
}
System.out.print(i + " ");
}
System.out.println("Countdown Aborted!");
}}

74
The return statement
• The return statement is used to exit from the current method.
• The flow of control returns to the statement that follows the original method call.
• The return statement has two forms: one that returns a value and one that doesn't.
• General form: return expression;
• To return a value, simply put the value (or an expression that calculates the value
after the keyword return.
• For example: return sum;
public double Sum(double x, double y) {
return sum = x+y;
}
• The data type of the value returned by return must match the type of the method's
declared return value. When a method is declared void, use the form of return that
doesn't return a value.
• For example: return;

75
The demonstration of return statement
public class Power {
private int x; // instance variables
private int y;
public Power(int a, int b) { //A constructor to Initializes instance variable
x=a;
y=b;
}
public double computePower() {//a method to access the data members
double z;
z=Math.pow(x,y);
return z;
}
public static void main(String args[]) {
Power p= Power(2,3); //Object creation with a parameterized constructor
double result=p. computePower(); //Assign the return value of the function to the variable res
System.out.println("Output :"+result);
}
}

76
End of Chapter two
ou
k y
a n
T h
Question???
Chapter three
object and class
3.1 overview
3.1.1 Class
 “Class” refers to a blueprint. It defines the variables
and methods the objects support
 A class is a group of objects that has common
properties. It is a template or blueprint from which
objects are created.
A class is declared by use of the class keyword. The
classes that have been used up to this point are
actually very limited examples of its complete form.
Classes can (and usually do) get much more complex.
The general form of a class definition is shown here:
Cont…
access specifiers class classname {
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list) {
// body of method
}
type methodname2(parameter-list) {
// body of method
}// ...
type methodnameN(parameter-list) {
// body of method
Cont…
Class Example:
Puplic class Employee {
// fields
String name;
double salary;
// a method
void pay () {
System.out.println("Pay to the order of " +
name + " $" + salary);
}}
Modifiers of the classes
• A class can also has modifiers
– public
• publicly accessible
• without this modifier, a class is only accessible within its
own package
– abstract
• no objects of abstract classes can be created
• The abstract modifier for creating abstract classes and
methods.
– final
– The final modifier for finalizing the implementations of
classes, methods, and variables.
• can not be subclasses
3.1.2 object
Objects
– An entity that has state and behavior is known as
an object e.g. chair, marker, pen, table, car etc. It
can be physical or logical (tengible and
intengible). The example of integible object is
banking system.
– Object is an instance of a class. Class is a template
or blueprint from which objects are created. So
object is the instance(result) of a class. Each
object has a class which defines its data and
behavior.
Continued…
• An object contains both data and methods that
manipulate that data
– The data represent the state of the object
– Data can also describe the relationships between
this object and other objects
• Example: A CheckingAccount might have
– A balance (the internal state of the account)
– An owner (some object representing a person)
• creating an object is instantiation
Simple Example of Object and Class

Public class Student1{


int id;//data member (also instance variable)
String name;//data member(also instance variable)

public static void main(String args[]){


Student1 s1=new Student1();//creating an object of Student
System.out.print(s1.id);
System.out.print(s1.name);
} }
Output:0 null
3.2 member methods and their components
Member methods are methods within that class.
The only required elements of a method declaration
are the method's return type, name, parentheses, (),
and a body between braces, {}.
More generally, method have six components, in
order:
• Modifiers—such as public, private, and others you
will learn about later.
• The return type—the data type of the value
returned by the method, or void if the method does
not return a value.
Cont…
• The method name—the rules for field names
apply to method names as well, but the
convention is a little different.
• The parameter list in parenthesis—a comma-
delimited list of input parameters, preceded by
their data types, enclosed by parentheses, (). If
there are no parameters, you must use empty
parentheses.
• An exception list—to be discussed later.
• The method body—enclosed between braces—
the method's code, including the declaration of
3.3 . instantiation and initializing class
objects
instantiation:
 In programming, instantiation is the creation of a
real instance or particular realization of an
abstraction or template such as a class of objects.
To instantiate is to create such an instance , for
example, defining one particular variation of object
within a class, giving it a name, and locating it in
some physical place.
 A class can be instantiated hundreds or thousands
of times, but each instantiation creates a new and
unique object.
Cont…
Instantiation is different that declaration, though, in
many cases, they happen at the same time.
For example:
Integer i;
is a declaration, telling us that i is a type of Object
known as Integer.
i = new Integer();
is an instantiation, where the variable i (who should
have previously been Declared) now has a specific
instance of it. That is, there is a structure created in
memory that is assigned to i.
Integer i = new Integer();
is a Declaration and Instantiation wrapped all
together.
Cont..
i = new Integer(10);
is an initialize, where the variable i (who
should have previously been instantiated) now
has a value of it.
Integer i = new Integer(10);
is a Declaration, Instantiation and initialization
wrapped all together.
Example
package geometric;
public class Geometric {
double width;
double height;
public Geometric(double w , double h){
width=w;
height=h;
}}
class GeometricDemo {
public static void main(String args[]) {
Geometric rectangle; //Object declaration with Geometric data type
rectangle = new Geometric(5.0,6.0); // Object instantiation and initialization
double area; Constructor
//assign values
rectangle.width=10;
rectangle.height =5;
// compute area of rectangle
area= rectangle.width * rectangle.height ;
System.out.println(" area is " + area);
3.4. constructors
constructors are code that is invoked to generate a
new object.
• A constructor is a (pre-)defined behavior that is
executed when a new instance is generated.
• its primary tasks are
1. to allocate a block of memory and
2. to initialize the object
• There are difference type of constructors.
These are default, parameterized.
Types of constructor
1. Default Constructor
2. parameterized ( Non-default Constructor)
1. Default Constructor
 Every class that does not explicitly declare
constructors automatically has a default
constructor.
 When a class declares an explicit constructor,
the default constructor is not generated.
 This constructor allocates the object and
initializes the instance variables according to
their declarations.
Default Constructor Example1
public class Person {
int age ;
String name;
public static void main(String args[]) {
Person x = new Person();
x.age=20;
default constructor
x.name=“Abebe”,
System.out.println(“Name =“+ x.name +”age=“+x.age);
}
}
Default Constructor Example2
Package Person;
Import java. util.*;
public class Person {
int age ;
String name;
public static void main(String args[]) {
Scanner sc=new Scanner(System.in)
Person ob = new Person();
//receive inputs from users
System.out.println(“enter name);
ob.name=sc.next();
System.out.println(“enter age”);
ob.age=sc.nextInt();
System.out.println(“Name =“+ ob.name +”age=“ob.age);
Non-default Constructor
constructors can have parameters
This is commonly used for initialization parameters
Example:
public class Person {
int age;
String name;
public Person( int anAge, String aName ) {
age = anAge;
name = aName;}
public static void main(String args[]) {
Person ob=new Person(20,”Abebe”)
System.out.println(“Name=“+ob. name+”age=“+ob. age);
}}
the default constructor “disappears” if any constructor is declared, so also in this case.
Overloading Constructors
You can have more than one constructor for the same class
This is an overloading situation
Which constructor will selected based on the parameters of the “new”
public class Person {
int age;
String name;
public Person( int anAge, String aName ) {
age = anAge;
name = aName;
}
public person( int anAge ) {
age = anAge;

}
}
Cont..
class personDemo {
public static void main(String args[]) {
Person p = new Person(41, “Eric de la Morte”); // first constructor
Person p = new Person(41); //second constructo
Person p = new Person(); // impossible
}
}
Constructor Behavior
A constructor looks very much like a method.
• It can only be called with a “new” statement.
• It cannot be called like a normal method.
• Its body code is executed like a method.
3.5 methods
At the most basic level, a method is a sequence
of statements that has been collected together
and given a name. The name makes it possible
to execute the statements much more easily;
instead of copying out the entire list of
statements, you can just provide the method
name.
Continue…
A program that provides some functionality can
be long and contains many statements.
A method groups a sequence of statements and
should provide a well-defined, easy-to-
understand functionality.
A method takes input, performs actions, and
produces output.
Continue..
A method is a named block of statements that
performs a specific task. Other languages use
the terms function or procedure instead of
method for this construct.
Regardless of what they are called, methods
allow you to create self-contained units that
perform the tasks necessary in a program.
The capability to divide the functionality of a
program into a number of separate methods
makes it easier to develop, test, and maintain
programs.
VOID METHODS AND VALUE-RETURNING
METHODS
There are two general categories of methods:
void methods and value-returning methods.
– A method that performs a task, but does not
return a value is called a void method.
– A value-returning method not only
performs a task, but also sends a value back
to the code that called it.
Useful method terms
The following terms are useful when learning
about methods:
– Invoking a method using its name is known
as calling that method.
– The caller can pass information to a method
by using arguments.
– When a method completes its operation, it
returns to its caller.
HOW WE CREATE A METHOD
To create a method you write a method
definition. A method definition includes the
method header and the method body.
– The method header, which is the beginning
of the method definition, gives important
information about the method, including its
name.
– The body is the group of statements,
enclosed in braces, which perform the
methods operation.
Method Declaration: Header
A method declaration begins with a method header A
method header consists of modifiers (optional),
return type, method name, parameter list and a
throws clause (optional)
types of modifiers
access control modifiers
abstract
the method body is empty. E.g.
abstract void
sampleMethod( );
static
represent the whole class, no a specific
object can only access static fields and
other static methods of the same class
final
cannot be overridden in subclasses
Continue…
Example of method header

class MyClass
{ …
static int min ( int num1, int num2 )

method parameter list


name
The parameter list specifies the type
return and name of each parameter
type
The name of a parameter in the method
properties declaration is called a formal argument
Method Declaration: Body
The header is followed by the method body:

class MyClass
{

static int min(int num1, int num2)
{
int minValue = num1 < num2 ? num1 : num2;
return minValue;
}

}
Continue…
The general form of a method definition is
scope type name(argument list) {
statements in the method body
} where scope indicates who has access to the method,
type indicates what type of value the method returns,
name is the name of the method, and argument list is a
list of declarations for the variables used to hold the
values of each argument.
The most common value for scope is private, which
means that the method is available only within its
own class. If other classes need access to it, scope
should be public instead . If a method does not
return a value, type should be void.
Example1
// This program includes a method inside the box class.
Public class Box {
double width;
double height;
double depth;
// display volume of a box
void volume() {
System.out.print("Volume is ");
System.out.println(width * height * depth);
}}
class BoxDemo3 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
Continue…
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to mybox2's instance variables */
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
// display volume of first box
mybox1.volume();
// display volume of second box
mybox2.volume();}
This program generates the following output.
Volume is 3000.0
Example 2:
Public class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Public Box(double w, double h, double d) {
width = w;
height = h;
depth = d;}
// compute and return volume
double volume() {
Continue…
class BoxDemo {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println(" Box 1 Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println(" Box 2 Volume is " + vol);}}
The output from this program is shown here:
Box 1 Volume is 3000.0
Box 2 Volume is 162.0
Example3
package rectangle;
import java.util.*;
public class Rectangle {
double w ;
double h;
void area(){
Scanner sc=new Scanner(System.in);
System.out.print("Enter width and height ");
w=sc.nextDouble();
h=sc. nextDouble();
double ar=w*h;
System.out.println("The area of is"+ar);
}
class imp{
public static void main(String[] args) {
Rectangle R1=new Rectangle();
R1.area();
}
}
2.5. access specifiers

An access specifier is a Java keyword that


indicates how a field or method can be
accessed.
public
– When the public access specifier is applied to a class
member, the member can be accessed by code inside the class
or outside.
private
– When the private access specifier is applied to a class
member, the member cannot be accessed by code outside the
class. The member can be accessed only by methods that are
members of the same class.
Access Modifiers
* Access modifiers define various levels of access between class members and the
outside world (other objects).
* They allow us to define the encapsulation characteristics of an object.
* There are four access modifiers in java:
1. private – Most restrictive, accessible only by its own class
2. protected – Accessible by its own class & derived/sub/child class
3. public - Accessible to anyone, both inside and outside the class(Have global visibility )
4. default - Accessible to only classes in the same package. No actual keyword for
declaring default access modifier, applied by default in the absence of any access
modifier.
Access Modifier Accessible from Accessible from Accessible from
own class derived class objects(Outside class)
public Yes Yes Yes
protected Yes Yes No
private Yes No No

116
2.6. accessors and mutators

Accessor method: A method of a class that only


accesses (that is, does not modify) the value(s)
of the data member(s).
Mutator method: A method of a class that
modifies the value(s) of the data member(s).
• Each field that the programmer wishes to be
viewed by other classes needs an accessor.
• Each field that the programmer wishes to be
modified by other classes needs a mutator.
2.7. calling and returning methods
How to invoke (call) a method (method invocation):
• When a method is invoked (called), a request is made to
perform some action, such as setting a value, printing
statements, returning an answer, etc. The code to invoke
the method contains the name of the method to be
executed and any needed data that the receiving method
requires. The required data for a method are specified in
the method's parameter list.
• You invoke (call) a method by writing down the calling
object followed by a dot, then the name of the method,
and finally a set of parentheses that may (or may not)
have information for the method.
Continue…
Each time a method is called, the values of the actual arguments
in the invocation are assigned to the formal arguments

int num = objectName.min (2, 3);

static int min (int num1, int num2)


{
int minValue = (num1 < num2 ? num1 : num2);
return minValue;
}
Returning a Value from a Method

 A method returns to the code that invoked


it when it completes all the statements in
the method, reaches a return statement.
 You declare a method's return type in its
method declaration. Within the body of the
method, you use the return statement to
return the value, which is usually written as
return expression;
where expression is a Java expression that
specifies the value you want to return.
Continue…
As an example, the method definition
private double feetToInches(double feet) {
return 12 * feet;
}
converts an argument indicating a distance in feet to
the equivalent number of inches, relying on the fact
that there are 12 inches in a foot.
2.8. static and instance members
Instance Methods and Variables
Methods and variables that are not declared as static are
known as instance methods and instance variables.
1. An instance variable is one per Object, every
object has its own copy of instance variable.
Eg:
public class Test{ int x = 5; }
Test t1 = new Test();
Test t2 = new Test();
Both t1 and t2 will have its own copy of x.
Continue…
2. A static variable is one per Class, every object
of that class shares the same Static variable.
Eg:
public class Test{ public static int x = 5; }
Test t1 = new Test();
Test t2 = new Test();
Both t1 and t2 will have the exactly one x to
share between them.
Class or Static Variables

• Variables are areas allocated by the computer memory to hold data.

Class variable Instance variable


Class variable is declared by using Instance variable is declared without
static keyword. static keyword.
static int a = 4; int a = 4;
All objects share the single copy of All objects have their own copy of
static variable. instance variable.
Belong to the whole class-static
member variable.
Static variable does not depend on Instance variable depends on the
the single object because it belongs object for which it is available.
to a class.
Static variable can be accessed without Instance variable cannot be accessed
creating an object, by using class name. without creating an object.
ClassName.variable ObjectName.variable
124
Class
s
or Static Methods
Static Method Instance Method
Static methods are declared by using instance methods are declared without
static keyword. static keyword.
static type method( ); type method( );
All objects share the single copy of All objects have their own copy of
static method. instance method.
Static method does not depend on the Instance method depends on the object for
single object because it belongs to a class. which it is available.

Static method can be invoked without Instance method cannot be invoked


creating an object, by using class name. without creating an object.
ClassName.method( ); ObjectName.method( );

Static methods cannot call non-static Non-static methods can call static
methods. methods.
Static methods cannot access none- Non-static methods can access static
static variables. variables.
125
Static methods cannot refer to this or Instance methods can refer to this and
super. super.
Examples of Static/Class Variables and Methods

•When to declare variable as static? When value of the variable remains the same for all class
instance created & being used in every instance. They’ll be loaded when a class loads.
•Static tells compiler there’s exactly one copy of this variable in existence, no matter how many
times class has been instantiated.
•Static method or variable is not attached with specific object, but to class as a whole. They are
allocated when the class is loaded.
Static methods are declared when the behavior of method doesn’t change for each object created
[i.e. behaviors of method remain the same for all instances created.]
// Demonstrate static variables, methods and blocks.
class UseStatic {
static int a = 3;
static int b;
static void meth ( int x ) { Output
System.out.println ( “ x = “ + x ); Static block
System.out.println ( “ a = “ + a ); Initialized
System.out.println ( “ b = “ + b ); x = 42
} a=3
static { System.out.println ( “ Static block initialized . “ ); b = 12
b=a*4;
}
public static void main ( String args [ ] ) { meth ( 42 ); }126
}
End of Chapter three
ou
k y
a n
T h
Question???
2016

Object-Oriented Programming
with Java
Information Technology Year II
Compiled by: Birhan H.

128
Chapter four

OOP Concepts
129
4.1. Concept of inheritance
inheritance: a parent-child relationship between classes.
 It allows sharing of the behavior of the parent class into
its child classes.
 one of the major benefits of object-oriented
programming (OOP) is this code sharing(reusability )
between classes through inheritance.
 child class can add new behavior or override existing
behavior from parent.
 Inheritance is a code re-use issue.
we can extend code that is already written in a
manageable manner.
Continue…
Take an existing object type (collection of fields
and methods) and extend it.
– create a special version of the code without
re-writing any of the existing code.
– End result is a more specific object type,
called the sub-class / derived class / child
class.
– The original code is called the superclass /
parent class / base class.
Terminolog
y
Inheritance is a fundamental Object Oriented concept

A class can be defined as a "subclass" of another class.


The subclass inherits data attributes of its super class
The subclass inherits methods of its super class

superclass:
Person
The subclass can: - name: String
Add new functionality - age: int
Use inherited functionality
Override inherited functionality
subclass: Employee
- employeeID: int
- salary: int
- startDate: Date
Types of inheritance in Java:
Single,Multilevel,Multiple
Below are Various types of inheritance in Java. We will
see each one of them one by one with the help of
flow diagrams
1) Single Inheritance:is easy to understand. When a
class extends another one class only then we call it
a single inheritance. The below flow diagram shows
that class B extends only one class which is A. Here
A is a parent class of B and B would be a child
class of A. A

B
(a) Single inheritance
Continue…
2) Multilevel Inheritance:Multilevel
inheritance refers to a mechanism in OO
technology where one can inherit from a
derived class, there by making this derived
class the base class for the new class. As you
can see in below flow diagram C is subclass or
child class of B and B is
A
a child class of A.

(b) Multilevel inheritance


Continue…
3)Multiple Inheritance:
Multiple inheritance is the capability of creating
a single class with multiple superclasses.
Unlike some other popular object oriented
programming languages like C++, java doesn’t
provide support for multiple inheritance in
classes. Java doesn’t support multiple
inheritance in classes because it can lead
to diamond problem and rather than
providing some complex way to solve it, there
are better ways through which we can achieve
Continue…
Diamond Problem
To understand diamond problem easily, let’s
assume that multiple inheritance was
supported in java. In that case, we could have
a class hierarchy like below image.
Continue…
The "diamond problem is an ambiguity that
arises when two classes B and C inherit from
A, and class D inherits from both B and C. If
there is a method in A that B and C has
overridden, and D does not override it, then
which version of the method does D inherit:
that of B, or that of C?
Inheritance syntax

class SubclassName extends SuperclassName


{
instance fields
methods
}
The keyword extends indicates that you are
making a new class that derives from an
existing class.
Inheritance Example1
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Inheritance example2

// A simple example of inheritance.


// Create a superclass.
class A {
int i, j;
void showij() {
System.out.println("i and j: " + i + " " + j);
}
}
Continue…
// Create a subclass by extending class A.
class B extends A {
int k;
void showk() {
System.out.println("k: " + k);
}
void sum() {
System.out.println("i+j+k: " + (i+j+k));
}
}
Continue…
class SimpleInheritance {
public static void main(String args[]) {
A superOb = new A();
B subOb = new B();
// The superclass may be used by itself.
superOb.i = 10;
superOb.j = 20;
System.out.println("Contents of superOb: ");
superOb.showij();
System.out.println();
Continue…
/* The subclass has access to all public members of
its superclass. */
subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
System.out.println("Contents of subOb: ");
subOb.showij();
subOb.showk();
System.out.println();
System.out.println("Sum of i, j and k in subOb:");
subOb.sum();
}}
Continue…
The output from this program is shown here:
Contents of superOb:
i and j: 10 20
Contents of subOb:
i and j: 7 8
k: 9
Sum of i, j and k in subOb:
i+j+k: 24
Continue…
 As you can see, the subclass B includes all of the
members of its super class, A. This is why subOb
can access i and j and call showij( ). Also, inside
sum( ), i and j can be referred to directly, as if
they were part of B.
 Even though A is a superclass for B, it is also a
completely independent,stand-alone class. Being
a superclass for a subclass does not mean that the
superclass cannot be used by itself. Further, a
subclass can be a superclass for another subclass.
Benefits of Inheritance
• One view of inheritance is that it provides a
way to specify some properties/behaviors that
all subclasses must exhibit
• Inheritance can be used to re-use code
Super classes and subclasses
• Super class, base class, parent class:
terms to describe the parent in the
relationship, which shares its
functionality.
• subclass, derived class, child class:
terms to describe the child in the
relationship, which accepts
functionality from its parent.
Protected members
If class member is “protected” then it will be accessible only to the
classes in the same package and to the subclasses.
The protected visibility modifier allows a member of a base class to
be accessed in the child
– protected visibility provides more encapsulation than public
does
– protected visibility is not as tightly encapsulated as private
visibility Book
protected int pages
All these methods can access the + getPages() : int
+ setPages(): void
pages instance variable.
Note that by constructor chaining Dictionary
rules, pages is an instance
+ getDefinitions() : int
variable of every object of class + setDefinitions(): void
Dictionary. + computeRatios() : double
Using this() and super()
• In method body, this is a reference to the
current object and super is a reference to its
parent.
• inside a constructor, you can use this to invoke
another constructor in the same class. This is
called explicit constructor invocation. It MUST
be the first statement in the constructor body if
exists.
super
super has two general forms.
 The first calls the super class’ constructor.
 The second is used to access a member of the
super class that has been hidden by a member
of a subclass. Each use is examined in next
slide .
Using super to Call Super class Constructors

A subclass can call a constructor method defined by its


superclass by use of the following form of super:
super(parameter-list);
Here, parameter-list specifies any parameters needed
by the constructor in the superclass. super( ) must
always be the first statement executed inside a
subclass’ constructor.
To see how super( ) is used, consider Example
// BoxWeight now uses super to initialize its Box
attributes.
Continue…
// A complete implementation of BoxWeight.
class Box {
double width;
double height;
double depth;
// constructor used when all dimensions specified
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;}
Continue…
// constructor used when no dimensions specified
Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; } // box
// constructor used when cube is created
Box(double len) {
width = height = depth = len;
}
// compute and return volume
double volume() {
return width * height * depth;
Continue…
class BoxWeight extends Box {
double weight; // weight of box
// constructor when all parameters are specified
BoxWeight(double w, double h, double d, double
m) {
super(w, h, d); // call superclass constructor
weight = m;}
Continue..
// default constructor
BoxWeight() {
super();
weight = -1;}
// constructor used when cube is created
BoxWeight(double len, double m) {
super(len);
weight = m;}
Continue…
class DemoSuper {
public static void main(String args[]) {
BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);
BoxWeight mybox2 = new BoxWeight(); // default
BoxWeight mycube = new BoxWeight(3, 2);
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
System.out.println("Weight of mybox1 is " +
mybox1.weight);
System.out.println();
Continue…

vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
System.out.println("Weight of mybox2 is " +
mybox2.weight);
System.out.println();
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
System.out.println("Weight of mycube is " +
mycube.weight);
}}
Continue…

This program generates the following output:


Volume of mybox1 is 3000.0
Weight of mybox1 is 34.3
Volume of mybox2 is -1.0
Weight of mybox2 is -1.0
Volume of mycube is 27.0
Weight of mycube is 2.0
A Second Use for super
The second form of super acts somewhat like this,
except that it always refers to the superclass of the
subclass in which it is used.This usage has the
following general form:
super. member
Here, member can be either a method or an instance
variable. This second form of super is most
applicable to situations in which member names of a
subclass hide members by the same name in the
super class. Consider this simple class hierarchy:
// Using super to overcome name hiding.

class A {
int i;}
// Create a subclass by extending class A.

class B extends A {
int i; // this i hides the i in A
B(int a, int b) {
super.i = a; // i in A
i = b; // i in B}
void show() {
System.out.println("i in superclass: " + super.i);
System.out.println("i in subclass: " + i);}}
Continue…

class UseSuper {
public static void main(String args[]) {
B subOb = new B(1, 2);
subOb.show();}}
This program displays the following:
i in superclass: 1
i in subclass: 2
Although the instance variable i in B hides the i in A,
super allows access to the I defined in the
superclass. As you will see, super can also be used
to call methods that are hidden by a subclass.
4.2 Polymorphism
• Polymorphism is the ability to create variables and methods that
has more than one form.
• Polymorphism is the quality that allows one interface to access a
general class of actions.

• Polymorphism – is achieved through


1. Method Overloading -defining methods in same class with
different signatures(parameters, type).
2. Method Overriding -defining methods in super and subclasses
with the same signature(parameter, type).

162
Method Overloading and Overriding
Method Overloading
Method Overloading is defining two or more methods with the same name within the same class.
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:
1) by the number of arguments, or
2) by the types of arguments
Overloading and inheritance are two ways to implement polymorphism.
When java call an overloaded method, it simply executes the version of the method whose
parameters match the arguments.
Two methods are overloaded if the:
1. No of parameters are different
2. Type of parameters is different
3. Order of parameters is different

163
1. No of parameters are different

public void add(int i) { System.out.println(i+i); } //Has only one parameter


public void add(int i, int j) { System.out.println(i+j); } //Has two parameter
public void add(int i, int j, int k) { System.out.println(i+j+k); } //Has three parameter

2. Type of parameters is different


public void add(int i, int j) { System.out.println(i+j); } //Has two integer type parameters
public void add(double i, double j) {System.out.println(i+j); } //Has two double type parameters
public void add(double i, int j) { System.out.println(i+j); } //Has one int & one double type parameters

3. Order of parameters is different


public void add(double i, int j) { System.out.println(i+j); } //Order is double and int
public void add(int i, double j) { System.out.println(i+j); } //Order is int and double

164
Example of Method Overloading
public class Area {
public void computeArea(double base, double height) {
double area = (base* height)/2;
System.out.println(“The area of Triangle is: ”+area);
}
public void computeArea(int width, int length) {
double area = width*length;
System.out.println(“The area of Rectangle is: ”+area);
}
public void computeArea(double radius) {
double area = Math.PI*radius* radius;
System.out.println(“The area of Circle is: ”+area);
}}
public class AreaTest {
public static void main(String args[]) {
Area a = new Area();
a. computeArea(7.5,5);
a. computeArea(7,5);
a.computeArea(10); 165

}
Method Overriding

• When a child class defines a method with the same name and signature as the parent,
then it is said that the child’s version overrides the parent’s version in his favor.
• When an overridden method is called from child class object, the version in the child
class is called not the parent class version.
• The return type, method name, number and type of the parameters of overridden method
in the child class must match with the method in the super class.
• You can call the super class variable & method from the child class with super keyword.
super.variablename; and super.overriddenMethodName();
• Method overriding by subclasses with different number and type of parameters.
public class Findareas {
public static void main (String []agrs){
Figure f= new Figure(10 , 10); //Create object(Figure instance variable) f
Rectangle r= new Rectangle(9 , 5); //Create object(Rectangle instance variable) r
Figure figref; //Create object variable figref of Figure
figref=f; //figref holds reference of f
System.out.println("Area is :"+figref.area()); //Calls method area() in Figure
figref=r; //figref holds reference of r
System.out.println("Area is :"+figref.area()); //Calls method area() in Rectangle overrides area in Figure
}}
166
class Figure {
double dim1; double dim2;
Figure(double a , double b) {
dim1=a; dim2=b;
}
double area() {
System.out.println("Inside area for figure.");
return(dim1*dim2);
}}
class Rectangle extends Figure {
Rectangle(double a, double b) { super(a ,b); //Calls Super class constructor }
double area() { //Overrides the method in Super class
System.out.println("Inside area for rectangle.");
return(dim1*dim2);
}}
//The method area() in the subclass Rectangle overrides the method area() in
the surer class Figure
Result:
The above code sample will produce the following result.
Inside area for figure. Area is :100.0
Inside area for rectangle. Area is :45.0 167
// Method overriding.
class A {
int i, j;
A(int a, int b) { i = a; j = b; }
void show() { // display i and j
System.out.println("i and j: " + i + " " + j); }
}
class B extends A {
int k;
B(int a, int b, int c) { super(a, b); k = c; }
void show() { // display k – this overrides show() in A
System.out.println("k: " + k); //k: 3
}}
class Override {
public static void main(String args[]) {
B b = new B(1, 2, 3);
b.show(); // this calls show() in B which overrides/ignores it!
168
}
public class Employee {
private String name; Example of Polymorphism!
private double salary;
Employee(String n, double s) { name =n; salary=s; } //Constructor
public void setName(String nm) { name=nm; }
public String getName() {return name; }
public void setSalary(double s) { salary=s; }
public double getSalary() { return salary; }
}
class Manager extends Employee {
private double bonus;
Manager(String n, double s, double b) { super(n, s); bonus=b; }
public void setBonus(double b) { bonus=b; }
public double getBonus() { return bonus; }
public double getSalary() { // method overriding. Overrides the getSalary() in Employee Class
double basesalary = super.getSalary(); // calls getSalary() method in super class
return basesalary + bonus; // manager salary is salary+bonus;
}}
class EmployeeMainClass {
public static void main(String[]args) {
Employee e = new Employee("Programmer",20000);
System.out.println( e.getName()+ ": "+e.getSalary()); //Programmer: 20000.0
Manager m = new Manager("Boss",20000,5000);
e = new Manager("Boss",20000,5000); // e = m;
169
System.out.println( e.getName()+”: ”+e.getSalary()); //Boss: 25000.0
}}
Encapsulation-Data/Info hiding
• Encapsulation is a programming mechanism that binds together code and the
data it manipulates, and that keeps both safe from outside interference and
misuse.
• Encapsulation is the concept of hiding the implementation details of a class and
allowing access to the class through a public interface.
• It hides certain details and only show the essential features of the object.
• For this, we need to declare the instance variables of the class as private or protected
& access only the public methods rather than accessing the data(instance
variable) directly.
• We can prevent access to our object's data by declaring them as private &
control access to them.
• How encapsulation is achieved?
If you declare private variables in source code, it will achieve encapsulation
because it restricts access to that particular data. This statement is true in all
cases.

170
Demonstration of Encapsulation

•In other words, encapsulation is the ability of an object to be a container (or capsule) for
related properties (i.e. data variables) and methods (i.e. functions).
public class Box {
private int length;
private int width;
private int height;
public Box(int len, int wid, int hei) { //Constructor
length=len; width=wid; height=hei;
}
public void setLength(int p) {length = p;} public int getLength() { return length;}
public void setWidth(int p) {width = p;} public int getWidth() { return width;}
public void setHeight(int p) {height = p;} public int getHeight() { return Height;}
public int displayVolume() {
System.out.println(getLength() * getWidth() * getHeight() ) ;
}
}
Public class MainBox {
public static void main(String args [ ]) {
Box b=new Box(3,4,5);
b.displayvolume(); //60
}} 171
• The ability to change the behavior of your code without changing your implementation
code is a key benefit of encapsulation.
• How to hide implementation details?
• Keep your class instance variables private or protected. But how could we access these
protected instance variables? Make our instance methods public and access private or
protected variables through public methods.
• For maintainability, flexibility, and extensibility
1.Keep instance variables protected (with an access modifier, often private).
2. Make public accessor methods, and force calling code to use those methods rather
than directly accessing the instance variable.
3. For the methods, use the Java naming convention of set and get.
public class Box {
private int size; // protect the instance variable. Only an instance of Box Class can access
it
// Provide public getters and setters
public int getSize() { return size; }
public void setSize(int newSize) { size = newSize; }
}
class BoxMain {
public static void main(String args[]) {
Box b=new Box(); //create instance of Box
b.setSize(25); //access methods trough box objects
System.out.println("Size:"+b.getsize()); //Size: 25 172
}
• The internal portion (variables) of an object has more limited visibility than
the external portion (methods) which will protect the internal portion
against unwanted external access.
• //First step is to create the variables of the object private so that nobody
can access them from outside.
public class Employee {
private double salary; //
• //Second step is to provide public setters and getters methods for accessing
the private variables.
public void setSalary(double salary) {this.salary = salary; }
public double getSalary() { return salary; }
}
• //Third step is to create an object in main method and access the public
methods
public class MainClass {
public static void main(String[] args) {
Employee emp = new Employee ();
emp.setSalary(2000); //set Salary to 2000
emp.getSalary(); //2000 173
}}
Implementing Business Logic with Encapsulation
public class Student {
private String ID;
private double cgpa;
public void setID(int ID) { this.ID = ID; }
public String getID() { return this.ID; }
}
public void setCGPA(double cgpa) {
if(cgpa<0 && cgpa>4) {
System.out.println(“Invalid CGPA”);
}
public class Employee {
else { this.cgpa = cgpa; }
private double salary; //Privately Protect salary }
public void setSalary(float salary) {
public double getCGPA() { return this.cgpa; }
if(salary<500 && salary>5000) {
System.out.println(“Salary Must be >=500”); }
} public class StudentMainClass {
else {
this.salary = salary; public static void main(String args[]) {
} String ID=“ETR/350/04”;
} double cgpa=3.25;
public float getSalary() { return salary; }
} Student stud = new Student();
public class EmpMainClass { stud.setID(ID); //set ID
public static void main(String args[]) {
double salary=2000; sutd.getID(); //ETR/350/04
Employee emp = new Employee(); sutd.setCGPA(cgpa); //set CGPA
emp.setSalary(salary); 174
stud.getCGPA(); //3.25
emp.getSalary(); //2000
} }}
Examples of Encapsulation

class Check { class Login {


private double amount=0; private String password;
public int getAmount(){ public int getPassword(){
return amount; return password;
} }
public void setAmount(double amt){ public String setPassword(String pass){
amount=amt; password=pass;
} }
} }
public class Mainclass { public class Mainclass {
public static void main(String[] args){ public static void main(String[] args) {
double amt=0; String Pass=“”;
Check obj = new Check(); Check obj = new Check();
obj.setAmount(200); //set amount to 200 obj.setPassword(“123”);//set password to 123
amt = obj.getAmount(); pass = obj.getPassword();
System.out.println("Your current System.out.println("Your Password is:
amount is: "+amt); "+pass); //Your Password is: 123
// Your current amount is: 200 }
} }
}
175
Demonstration of Encapsulation
• Let's suppose that you need a class that gets control on debits and credits in a
bank account. This is critical. Let's suppose that you declare as public the
attribute 'balance'. Now suppose that you or another programmer which is
using your class made a mistake in somewhere in the code and just before
saving changes to database he did something like:
nameObject.balance =someValue;
• In this way he has changed directly the balance of the account. That is wrong
because it must be changed just by using additions '+' and subtractions '-'
(credits and debits).
Using encapsulation we can help that:
class BankAccount {
private double balance;
private double init;
private double debit;
private double credit;
public BankAccount(double ini, double deb, double cre){
init = ini; debit = deb; credit = cre;
balance = init + credit - debit; //initialize the balance
} 176
public double getDebit() { return debit; }
//add to debit and sub from balance
public void setDebit(double debit) {
this.debit += debit;
balance -= debit;
}
public double getCredit() { return credit; }
//add to credit and add to balance
public void setCredit(double credit) {
this.credit += credit;
balance += credit;
}
public double getBalance() { return balance; }
public double getInit() { return init; }
}
public class BankAcct {
public static void main(String[] args) {
BankAccount bacct = new BankAccount (50,200,300);
System.out.println("Your Current Balance is: "+bacct.getBalance());
177
}
Abstract Classes
• An abstract class is a class that is partially implemented and whose purpose is solely
represent abstract concept.
• Abstract classes are made up of one or more abstract methods.
• Abstract classes cannot be instantiated because they represent abstract concept.
• When we do not want to allow any one to create object of our class, we define the class as
abstract.
• Contain fields that are not static and final as well as implemented methods
• public class Animal { } is an abstraction used in place of an actual animal
• Abstraction is nothing but data hiding. It involves with the dealing of essential
information.
• Abstract classes are those that works only as the parent class or the base class. Subclasses
are derived to implement.
• Declared using abstract keyword
• An abstract method is a method which has no implementation (body).
• The body of this method is provided by a subclass of the class in which the abstract
method is declared.
• Abstract class can’t be instantiated(Object can’t be created), but can be extended to sub
classes
• Lets put common method name in one abstract class
• An abstract class can inter mix abstract and non abstract methods.
• Abstract class and method cannot be declared as final. 178

• Abstract method cannot be declared as static.


Abstract Class Example 1 in Java Program.

//An Other Example of Abstract Classes


abstract class Shape {
abstract void draw();
}
class Rectangle extends Shape{
void draw() {
System.out.println(“Drawing Rectangle”);
}}
class Traingle extends Shape{
void draw(){
System.out.println(“Drawing Traingle”);
}}
class AbstractDemo {
public static void main(String args[]) {
Shape s1=new Rectangle();
s1.draw();
s1=new Traingle();
s1.draw();
}
}
Result:
Drawing Rectangle
Drawing Traingle
179
Abstract Class Example in Java Program.

public class Rectangle extends TwoDShape { public class AbstractMain {


Rectangle() { // A default constructor.
super(); //Calls Super Class Constructor public static void main(String[] args) {
} // TODO code application logic here
// Constructor for Rectangle. //Create objects of subclasses using the abstract class
Rectangle(double w, double h) {
super(w, h, "Rectangle"); TwoDShape t = new Triangle("Right", 8.0, 12.0);
} TwoDShape r = new Rectangle(10, 4);

boolean isSquare() { System.out.println("Object is " +t.getName());


if(getWidth() == getHeight()) { System.out.println("Area is " + t.area());
return true; System.out.println();
} System.out.println("Object is " +r.getName());
return false; System.out.println("Area is " + r.area());
} System.out.println();
double area() {
return getWidth() * getHeight(); }
} }
}

180
Abstract Class Example 3 in Java Program.

• Abstraction is more like data hiding. You create a class with abstract methods. This
methods are the common for all objects which inherit from the abstract class but
every class implements these methods as they need. The main idea is that you can
declare an attribute of the an abstract class and this attribute can hold any object
that inherit from that abstract class. for example:
abstract class Car {
public abstract void ignition();
}
class Mazda extends Car {
public void ignition() { System.out.println("Code for starts Mazda engine");}
}
class Audi extends Car {
public void ignition() {
System.out.println("Code for starts Audi engine");
}}
public class Test {
public static void main(String[] args) {
Car car = new Mazda();
car.ignition();
car = new Audi ();
car.ignition(); 181

}}
Demonstration of Abstract Classes Example 4
abstract class Employee {
private String name;
private String address;
protected double salary;
public Employee(String name, String address, double salary) {
this.name = name;
this.address = address;
this.salary = salary;
}
public abstract double raise(); // abstract method
}
class Secretary extends Employee {
Secretary(String name, String address,double salary) {
super(name, address, salary); //Calls super class constructor to initialize data members
}
public double raise(){
return salary;
}
} 182
class Salesman extends Employee{
private double commission;
public Salesman(String name, String address, double salary, double commission) {
super(name, address, salary); //Calls super class constructor
this.commission=commission;
}
public double raise() {
salary = salary + commission;
return salary;
}
}
class Manager extends Employee {
Manager(String name, String address,double salary) {
super(name, address, salary); //Calls super class constructor
}
public double raise(){
salary = salary + salary * .05;
return salary;
} 183
}
class Worker extends Employee {
Worker(String name, String address, double salary) {
super(name, address, salary); //Calls Super Class Constructor
}
public double raise() {
salary = salary + salary * .02;
return salary;
}
}
public class Main {
public static void main(String[] args) {
Secretary a=new Secretary(“Abraham”,”Assosa”,1000);
Manager b=new Manager(“Worku”,”Assosa”,2000);
Worker c= new Worker(“Aster”,”Assosa”,1000);
Salesman d= new Salesman(“Daniel”,”Assosa”,1500,200);
Employee[] ArrayEmployee=new Employee[4];
ArrayEmployee[0]=a;
ArrayEmployee[1]=b; Output
ArrayEmployee[2]=c; Final Salary: 1000.0
ArrayEmployee[3]=d;
Final Salary: 2100.0
for(int i=0;i< ArrayEmployee.length; i++){
double s = ArrayEmployee[i].raise(); Final Salary: 1020.0
System.out.println(“Final Salary: “+s); Final Salary: 1700.0
184
}}
}
End of Chapter four
ou
k y
a n
T h
Question???
2016

Object-Oriented Programming
with Java
Information Technology Year II
Compiled by: Birhan H.

186
CHAPTER 5
EXCEPTION
HANDLING AND
THREAD
Contents
 Fundamentals of Exception Handling

Types of exceptions

use of try and catch ,throw, throws,


and the finally keyword
 Multithreading
5.1 Fundamentals of exception handling
 A Java exception is an object that describes an
exceptional (that is, error) condition that has
occurred in a piece of code.
 When an exceptional condition arises, an
object representing that exception is created
and thrown in the method that caused the
error.
 Exceptions can be generated by the Java run-
time system, or they can be manually
generated by your code.
 Exception handling enables a program to deal
with exceptional situations and continue its
normal execution.
 Runtime errors occur while a program is
running if the JVM detects an operation that
is impossible to carry out.
Example:
 ArrayIndexOutOfBoundsException
 InputMismatchException.( entering integer values
for double)
 In Java, runtime errors are thrown as
exceptions.
 Java exception handling is managed via five
keywords: try, catch, throw, throws, and
finally.
 The general form of an exception-handling
block:
try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ...
finally {
// block of code to be executed after try block ends
}
5.2 Types of exceptions
 All exception types are subclasses of the built-
in class Throwable.
5.3 Using try and catch, throw, throws, and
finally
 Are used to handle an exception by yourself.
 Benefit :
First, it allows you to fix the error.
Second, it prevents the program from automatically
terminating.
 To handle a run-time error, simply enclose the
code that you want to monitor inside a try
block.
 Immediately following the try block, include a
catch clause that specifies the exception type
that you wish to catch.
class Exc2 {
public static void main(String args[]) {
int d, a;
try { // monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
} catch (ArithmeticException e) { // catch divide-by-zero error
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}}
output:
Division by zero.
After catch statement.
 The scope of the catch clause is restricted to
those statements specified by the
immediately preceding try statement.

 A catch statement cannot catch an exception


thrown by another try statement (except in
the case of nested try statements).

 The statements that are protected by try must


be surrounded by curly braces.
Multiple catch Clauses
 is used to handle more than one exceptions
 each clause catching a different type of
exception.
 When you use multiple catch statements, it is
important to remember that exception
subclasses must come before any of their
superclasses.
 This is because a catch statement that uses a
superclass will catch exceptions of that type
plus any of its subclasses.
throw
 It is possible for your program to throw an
exception explicitly, using the throw statement.
 The general form of throw is shown here:
throw ThrowableInstance;
 ThrowableInstance must be an object of type
Throwable or a subclass of Throwable.
 There are two ways you can obtain a
Throwable object:
 using a parameter in a catch clause, or creating
one with the new operator.
throws
 If a method is capable of causing an exception
that it does not handle, it must specify this
behavior so that callers of the method can
guard themselves against that exception.
 by including a throws clause in the method’s
declaration.
 A throws clause lists the types of exceptions
that a method might throw.
 This is necessary for all exceptions, except
those of type Error or RuntimeException, or
any of their subclasses.
 The general form of a method declaration that
includes a throws clause:
type method-name(parameter-list) throws
exception-list
{
// body of method
}
 exception-list is a comma-separated list of the
exceptions that a method can throw.
finally
 finally creates a block of code that will be
executed after a try/catch block has
completed and before the code following the
try/catch block.
 finally clause will execute whether or not an
exception is thrown.
 If an exception is thrown, the finally block will
execute even if no catch statement matches
the exception.
5.4 Multithreading
The Java Thread Model
 Java is a multithreaded programming
language .
 A multithreaded program contains two or
more parts that can run concurrently and
each part can handle different task at the
same time.
 Multithreading enables you to write in a way
where multiple activities can proceed
concurrently in the same program.
Life Cycle of a Thread:
 A thread goes through various stages in its life
cycle.
 For example, a thread is born, started, runs,
and then dies.
 Its life cycle is as follows:
 New: A new thread begins its life cycle in the
new state. (born)
 Runnable: After a newly born thread is started,
the thread becomes runnable.
 Waiting: Sometimes, a thread transitions to
the waiting state while the thread waits for
another thread to perform a task.
 Timed waiting: A runnable thread can enter
the timed waiting state for a specified interval
of time.
 Terminated: A runnable thread enters the
terminated state when it completes its task or
otherwise terminates.
Thread Priorities:
 Every Java thread has a priority that helps the os
determine the order in which threads are
scheduled.
 Java thread priorities are in the range between:
– MIN_PRIORITY (a constant of 1)
– MAX_PRIORITY (a constant of 10).
– NORM_PRIORITY (a constant of 5).
 Threads with higher priority should be allocated
processor time before lower-priority threads.
 A thread’s priority is used to decide when to
switch from one running thread to the next.
Synchronization
 is a way for you to enforce synchronicity of
thread when you need it.
 For example, if you want two threads to
communicate and share a complicated data
structure, such as a linked list, you need some
way to ensure that they don’t conflict with
each other.
 That is, you must prevent one thread from
writing data while another thread is in the
middle of reading it.
Messaging
 After you divide your program into separate
threads, you need to define how they will
communicate with each other.
 Java provides a clean, low-cost way for two or
more threads to talk to each other, via calls to
predefined methods that all objects have.
 Java’s messaging system allows a thread to
enter a synchronized method on an object,
and then wait there until some other thread
explicitly notifies it to come out.
The Thread Class and the Runnable Interface
 Java’s multithreading system is built upon the Thread
class, its methods, and its companion interface,
Runnable.
 To create a new thread, your program will either extend
Thread or implement the Runnable interface.
 The Thread class defines several methods that help
manage threads.
getName Obtain a thread’s name.
getPriority Obtain a thread’s priority.
isAlive Determine if a thread is still running.
join Wait for a thread to terminate.
run Entry point for the thread.
sleep Suspend a thread for a period of time.
Start Start a thread by calling its run method.
The Main Thread
 is a thread where thread begins running or
the one that is executed when your program
begins.
The main thread is important for two reasons:
o It is the thread from which other “child”
threads will be spawned (created).
o Often, it must be the last thread to finish
execution because it performs various
shutdown actions.
 Although it is created automatically when
your program is started, it can be controlled
through a Thread object.
 To do so, you must obtain a reference to it by
calling the method currentThread( ), which is
a public static member of Thread.
 Its general form is :
static Thread currentThread( )
 Once you have a reference to the main thread,
you can control it just like any other thread.
Creating a Thread
 In the most general sense, you create a
thread by instantiating an object of type
Thread.

 Java defines two ways in which this can be


accomplished:
• You can implement the Runnable interface.
• You can extend the Thread class, itself.
Implementing Runnable
 The easiest way to create a thread is to create
a class that implements Runnable.
 Runnable abstracts a unit of executable
code.
 You can construct a thread on any object that
implements Runnable.
 To implement Runnable, a class need only
implement a single method called run( ),
 Inside run( ), you will define the code that
constitutes the new thread.
 run( ) can call other methods, use other
classes, and declare variables, just like the
main thread can.
 The only difference is that run( ) establishes
the entry point for another, concurrent
thread of execution within your program.
 After you create a class that implements
Runnable, you will instantiate an object of
type Thread from within that class.
Extending Thread
 The second way to create a thread is to create
a new class that extends Thread.
 The extending class must override the run( )
method, which is the entry point for the new
thread.
 It must also call start( ) to begin execution of
the new thread.
End of Chapter five
ou
k y
a n
T h
Question???
GRAPHICAL USER INTERFACE
DESIGN CLASS.
217
CHAPTER 6
GRAPHICAL USER
INTERFACE
Contents :
 AWT
 Swing
6. 1 GUI
 A UI is an effective means of making
applications user-friendly.
 GUI are introduced by AWT class libraries.
 Swing introduced after AWT

AWT
 fine for developing small GUI, but not for
comprehensive project.
 prone to platform-specific bugs.
Swing
 a more robust, versatile, and flexible library .
 is uniform between platforms.
 provides richer implementations than does the AWT
 is designed to solve AWT’s problems.
 many AWT classes are used either directly or
indirectly by Swing.
 The Swing GUI component classes are named with a
prefixed J.

Today, most Java programs employ user interfaces


based on Swing.
6.2 AWT classes
 contained in the java.awt package
 AWT defines windows according to a class
applet and frame.
 contains component and container abstract
class and their sub classes.
 All user interface elements subclass of
component.
• The Container class is a subclass of
Component that allow other Component
objects to be nested within it.
SWING GUI
 contains classes that can be classified into
three groups:
• component classes
• container classes, and
• helper classes.
 The subclasses of Component are called
component classes
 JFrame, JPanel, and JApplet, are called
container classes used to contain other
components.
 The classes, such as Graphics, Color, Font,
FontMetrics, and Dimension, are called helper
classes used to support GUI components.

 Component is the root class of all the user-


interface classes including container classes

 JComponent is the root class of all the


lightweight Swing components.
 To work with AWT components, use
Containers, Window: Panel, Applet, Frame,
and Dialog.
 To work with Swing components, use
Containers, JFrame, JDialog, JApplet, and
JPanel.

 JApplet is a base class for creating a Java


applet using Swing components.
 The helper classes are not subclasses of
Component.
 They are used to describe the properties of
GUI components.
Frame
 is a window for holding other GUI
components.
 To create a user interface, you need to create
either a frame or an applet to hold the user
interface components.
 To create a frame, use the JFrame class
 javax.swing.JFrame :-is a top-level container
for holding other Swing user-interface
components .
 javax.swing.JPanel :-is an invisible container
for grouping user-interface components.
 javax.swing.Japplet:- is a base class for
creating a java applet using Swing
components.
 javax.swing.Jdialog:- is a popup window
generally used as a temporary window to
receive additional information from the user
or to provide notification to the user.
import javax.swing.JFrame;
public class MyFrame {
public static void main(String[] args) {
JFrame frame = new JFrame("MyFrame"); // frame
frame.setSize(400, 300); // Set the frame size
frame.setLocationRelativeTo(null);// Center a frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_C
LOSE);
frame.setVisible(true); // Display the frame
}}
Adding Components to a Frame
 Use the add method to add component
import javax.swing.*;
public class MyFrameWithComponents {
public static void main(String[] args) {
JFrame frame = new JFrame("MyFrameWithComponents");
// Add a button to the frame
JButton jbtOK = new JButton("OK");
frame.add(jbtOK);
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null); // Center the frame
frame.setVisible(true);
}}
Layout Managers
 is an object responsible for laying out the GUI components in
the container.
 is created using a layout manager class.
 are set in containers using the setLayout(aLayoutManager)
method.
 The three basic layout managers: FlowLayout, GridLayout,
and BorderLayout.
 FlowLayout is the simplest layout manager which components
are arranged in the container from left to right.(default)
FlowLayout.RIGHT, FlowLayout.CENTER, or
FlowLayout.LEFT.
 Example Set FlowLayout, aligned left with horizontal gap 10
and vertical gap 20 between components
 setLayout(new FlowLayout(FlowLayout.LEFT, 10, 20) );
 The GridLayout manager arranges components in a
grid (matrix) formation.
• The components are placed in the grid from left to
right, starting with the first row.
 You can specify the number of rows and columns in the
grid.
setLayout(new GridLayout(3, 2, 5, 5));
The BorderLayout manager divides a container into five
areas: East, South, West, North, and Center.
BorderLayout.EAST
setLayout(new BorderLayout(5, 10) );
add(new JButton("East"), BorderLayout.EAST);
Using Panels as Sub containers
 used as Sub containers to group GUI
components
 The Swing version of panel is JPanel.
 The following code creates a panel and adds a
button to it:
• JPanel p = new JPanel();
• p.add(new JButton("OK"));
The Color Class
 Colors are objects created from the Color class.
( for components)
 First import java.awt.Color; to set color for
component
 Colors are made of red, green, and blue
components, each represented by an int value
( from 0 to 255)
public Color(int r, int g, int b);
• JButton jbtOK = new JButton("OK");
• jbtOK.setBackground(color);
• jbtOK.setForeground(new Color(100, 1, 1));
Font class
 Fonts are objects created from the Font class.
public Font(String name, int style, int size);
• Font font1 = new Font("SansSerif", Font.BOLD, 16);
• Font font2 = new Font("Serif", Font.BOLD +
Font.ITALIC, 12);
• Font font3 = new Font("Serif", Font.BOLD +
Font.ITALIC, 12);
• JButton jbtOK = new JButton("OK");
• jbtOK.setFont(font1);
Common Features of Swing GUI Components
 The Component class is the root for all GUI
components and containers.
 All Swing GUI components (except JFrame, JApplet, and
JDialog) are subclasses of JComponent.
Image Icons
 Image icons can be displayed in many GUI components
using the ImageIcon class.
 Images are normally stored in image files.
 An image icon can be displayed in a label or a button
using new JLabel(imageIcon) or new JButton(imageIcon).
 Java currently supports three image formats.
GIF , JPEG , PNG .
ImageIcon icon = new ImageIcon("image/us.gif");
Jbutton
 A button is a component that triggers an action
when clicked.
 are defined in javax.swing.AbstractButton.
 A button has a default icon, a pressed icon, and a
rollover icon.
 A pressed icon is displayed when a button is
pressed.
 a rollover icon is displayed when the mouse is over
the button but not pressed.
JCheckBox
 A check box has one of two states: checked or
unchecked.
Example
 It inherits all the properties from
AbstractButton.

• JCheckBox jchk = new JCheckBox();


 To see if a check box is selected, use the
isSelected() method.
JRadioButton
 To create a radio button, use the
JRadioButton class.
Example
 enable you to choose a single item from a
group of choices.
 JRadioButton jrb = new JRadioButton();
 To group RadioButtons use:
ButtonGroup group = new ButtonGroup();
Labels
 To create a label, use the JLabel class.
 It is often used to label other components
(may be text or image)
JLabel jl = new Jlabel();
Text Fields
• To create a text field, use the JTextField class.
• A text field can be used to enter or display a
string.
(setText(newtext) and getText() respe.)
JTextField jtfMessage = new JTextField();
Text Areas
 uses to enter multiple lines of text.
JTextArea jtaNote = new JTextArea();
 JTextArea does not handle scrolling, but you
can create a JScrollPane object.
Combo Boxes
 choice list or drop-down list, contains a list of
items from which the user can choose.( to
choose one entry)
 Example country
JComboBox jcb = new JComboBox(new objects[]
{“Item1”,”Item2”…….});
Lists
 Basically performs the same function as a
combo box.
 Enables the user to choose a single value or
multiple values.
 JList jlst = new Jlist();
 Example
Menus
 Java provides five classes that implement
menus: JMenuBar, JMenu, JMenuItem,
JCheckBoxMenuItem, and
JRadioButtonMenuItem.

 JMenuBar is a top-level menu component


used to hold the menus which holds items.
Creating menus
1.Create a menu bar and associate it with a
frame or an applet by using the
setJMenuBar() method.
JMenuBar jmb = new JMenuBar();
frame.setJMenuBar(jmb);
2. Create menus and associate them with the
menu bar.
JMenu fileMenu = new JMenu("File");
jmb.add(fileMenu);
3. Create menu items and add them to the
menus.
fileMenu.add(new JMenuItem("New"));
4. The menu items generate ActionEvent.
Your listener class must implement the
ActionListener and the actionPerformed
handler to respond to the menu selection.
Popup Menus
 Is like a regular menu, but does not have a
menu bar and can float anywhere on the
screen.

 Creating a popup menu is similar to creating a


regular menu.
JPopupMenu jPopupMenu = new
JPopupMenu();
JOptionPane Dialogs
 A dialog box is normally used as a temporary
window to receive additional information
from the user or to provide notification that
some event has occurred.

 Java provides the JOptionPane class, which


can be used to create standard dialogs.
The Graphics Class in swing
 Each GUI component is an object of the
Graphics class.
 has methods for drawing strings, lines,
rectangles, ovals, arcs, polygons…
 Each component has its own coordinate
system with the origin (0, 0) at the upper-left
corner.
 The x-coordinate increases to the right, and
the y-coordinate increases downward.
Drawing Strings, Lines, Rectangles, and Ovals
 You can draw strings, lines, rectangles, and
ovals in a graphics context.
 The drawString(String s, int x, int y) method
draws a string starting at the point (x, y).

 The drawRect(int x, int y, int w, int h) method


draws a plain rectangle, and the fillRect(int x,
int y, int w, int h) method draws a filled
rectangle
 To draw an oval in outline or filled solid, you
can use either the drawOval(int x, int y, int w,
int h) method or the fillOval(int x, int y, int w,
int h) method.

 You can use the FontMetrics class to measure


the width and height of a string in the
graphics context.
Event-Driven Programming
 To respond to a button click, you need to
write the code to process the button-clicking
action.

 You need to create an object capable of


handling the action event on a button.

 This object is called an event listener.


Events and Event Sources
 An event is an object created from an event
source.

 When you run a Java GUI program, the


program interacts with the user, and the
events drive its execution.

• This is called event-driven programming.


 The component that creates an event and
fires it is called the event source object, or
simply source object or source component.
 The root class of the event classes is
java.util.EventObject.
 For example, a button is the source object for
a button clicking action event.

 You can identify the source object of an event


using the getSource() instance methods.
Listeners, Registrations, and Handling Events
 A listener is an object that must be registered
with an event source object.
 For an object to be a listener for an event on
a source object, two things are needed.

1. The listener object must be an instance of


the corresponding event-listener interface to
ensure that the listener has the correct
method for processing the event.
2. The listener object must be registered by the
source object. Registration methods depend on the
event type. For ActionEvent, the method is
addActionListener().

Mouse Events
 A mouse event is fired whenever a mouse button
is pressed, released, or clicked, the mouse is
moved, or the mouse is dragged onto a
component.
 Java provides two listener interfaces,
MouseListener and MouseMotionListener, to
handle mouse events.
Key Events
 A key event is fired whenever a key is
pressed, released, or typed on a component.

 The KeyEvent object describes the nature of


the event (namely, that a key has been
pressed, released, or typed) and the value of
the key.
CHAPTER 7
JDBC
JDBC ( Java database connectivity) Overview
 is Java API for developing Java database
applications .
 supports Java programs that accessing and
manipulating relational databases.

 is a set of Java interfaces and classes used to


write Java programs for accessing and
manipulating relational databases.
 JDBC driver serves as the interface to facilitate
communications between JDBC and a proprietary
database
 JDBC drivers are database specific and are
normally provided by the database vendors.
 MySQL JDBC drivers to access the MySQL
database
 Oracle JDBC drivers to access the Oracle
database.
 For the Access database, use the JDBC-ODBC
bridge driver included in JDK.
 An ODBC driver is preinstalled on Windows.
Developing Database Applications Using JDBC
 The JDBC API consists of classes and
interfaces :
 for establishing connections with databases
 sending SQL statements to databases
 processing the results of the SQL statements
 Four key interfaces are needed to develop
any database application using Java:

 Driver, Connection, Statement, and ResultSet

 The JDBC API defines these interfaces.


 The relationship of these interfaces is as
follows:
 A JDBC application:
 loads an appropriate driver using the Driver
interface,
 connects to the database using the
Connection interface,
 creates and executes SQL statements using
the Statement interface,
 processes the result using the ResultSet
interface if the statements return results.
A typical Java program takes the following
steps to access the database.
1. Loading drivers.
o An appropriate driver must be loaded using
the statement shown below before
connecting to a database.
o Class.forName("JDBCDriverClass");
• A driver is a concrete class that implements
the java.sql.Driver interface.
 JDBC Drivers
Database DriverClass
• Access sun.jdbc.odbc.JdbcOdbcDriver
• MySQL com.mysql.jdbc.Driver
• Oracle oracle.jdbc.driver.OracleDriver
2. Establishing connections.
 To connect to a database:use the static
method getConnection(databaseURL) in the
DriverManager class.

 Connection connection =
DriverManager.getConnection(databaseURL);

 where databaseURL is the unique identifier of


the database on the Internet.
 JDBC URLs
Database URL Pattern
Access jdbc:odbc:dataSource
MySQL jdbc:mysql://hostname/dbname
Oracle jdbc:oracle:thin:@hostname:port#:
oracleDBSID

EXAMPLE:Connection connection =
DriverManager.getConnection
("jdbc:odbc:ExampleMDBDataSource");
• Connection connection =
DriverManager.getConnection
• ("jdbc:mysql://localhost/javabook", "scott",
"tiger");

• Connection connection =
DriverManager.getConnection
("jdbc:oracle:thin:localhost:1521:orcl","scott",
"tiger");
3. Creating statements
 Creating a Statement object enables you to
send queries and commands to the database.

 Once a Connection object is created, you can


create statements for executing SQL
statements.

Statement statement =
connection.createStatement();
4. Executing statements.
 An SQL DDL or update statement can be
executed using executeUpdate(String sql),
and an SQL query statement can be executed
using executeQuery(String sql).

 The result of the query is returned in


ResultSet.
• create table Temp (col1 char(5), col2 char(5)):
• statement.executeUpdate("create table Temp
(col1 char(5), col2 char(5))");
• To select firstName, mi, lastName from Student
where lastName = 'Smith':
ResultSet resultSet = statement.executeQuery("select
firstName, mi, lastName from Student where
lastName " + " = 'Smith'");

5. Processing ResultSet.
 The ResultSet maintains a table whose current row
can be retrieved.
while (resultSet.next())
System.out.println(resultSet.getString(1) + " " +
resultSet.getString(2) + ". " + resultSet.getString(3));
6. Close the connection
 When you are finished performing queries
and processing results:
 you should close the connection, releasing
resources to the database.
connection.close();
import java.sql.*;
public class showsample {
public static void main(String[] args) {
String driver = " com.mysql.jdbc.Driver ";
String url = "jdbc:mysql://localhost:3306/sample";
String username = "root"; //
String password = ""; //
showsample(driver, url, username, password);}
public static void showsample(String driver, String url, String username,String password) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection =DriverManager.getConnection(url, username, password);
Statement statement = connection.createStatement();
String query ="SELECT fname, lname FROM sample";
ResultSet resultSet = statement.executeQuery(query);
while(resultSet.next()) {
System.out.print(resultSet.getString("fname") + " ");
System.out.println(resultSet.getString("lname"));}
connection.close();
} catch(ClassNotFoundException cnfe) {
System.err.println("Error loading driver: " + cnfe);
} catch(SQLException sqle) {
System.err.println("Error with connection: " + sqle);
THANK U
THE END OF THE
CHAPTER!

You might also like