OOP ch1
OOP ch1
with Java
Information technology Year II
1
Chapter One
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…
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…
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…
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…
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…
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…
Object-Oriented Programming
with Java
Information Technology Year II
Compiled by: Birhan H.
30
Chapter Two
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
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
static declares that a field or a method belongs to a class rather than an object
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;
42
2.5.2 Basic Data Types
43
Summary of Java Primitive Data Types
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 =.
47
2.6.2 Arithmetic Operators
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 !=.
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.
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.
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()
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
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:
• 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)
{
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
}
}
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 )
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
116
2.6. accessors and mutators
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
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.
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…
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.
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
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
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
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.
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.
Connection connection =
DriverManager.getConnection(databaseURL);
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.
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).
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!