ITTutor Advanced Java (1)
ITTutor Advanced Java (1)
1
Advanced Programming
Tutorial
2
Tutorial Outlines
OOP Concepts in java class Abstraction Inheritance
Object Encapsulation polymorphism
Polymorphism
4
Abstraction
It is used to represent the essential feature without representing the back ground details.
Abstraction focus on what the object does instead of how it does it.
5
Abstraction (Cont.…)
Real world Example of Abstraction: - Suppose we have an object Mobile Phone.
Necessary and Common Information) for the object "Mobile Phone" is make
a Call to any number and can send SMS.“
So that, for mobile phone object we will have abstract class like following:
6
Abstraction(Cont....)
abstract class MobilePhone pho ne
M obile
{ o al l
n t
public void Calling(); om mo
//C
public void SendSMS();
}
Public class Nokia1400 extends MobilePhone{
public class Blackberry extends MobilePhone
}
{
Public class Nokia2700 extends MobilePhone
{ public void FMRadio();
public void FMRadio(); Public void MP3();
Public void MP3(); Public void Camera();
Public void Camera(); Public void FMRadio();
} Public void Recording();
Public void ReadAndSendEmails();
}
7
Encapsulation
It is Wrapping up data member and method together into a single unit (i.e. Class).
Encapsulation means hiding the internal details of an object, i.e. how an object does
something.
10
Inheritance
The derived class inherits the states and behaviors from the base class.
The derived class is also called subclass and the base class is also known as superclass.
The derived class can add its own additional variables and methods which differentiates the
When a Class extends another class it inherits all non private data members
Inheritance
extends and implements keywords are used to describe inheritance in Java.
Inheritance
Inheritance
Types of Inheritance
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
1. Single Inheritance:
When a class extends another one class only, then we call it a single inheritance.
The 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.
Inheritance Single Inheritance example program in Java
Single Inheritance
with final class A
Inheritance
2) Multilevel Inheritance:
Multilevel inheritance refers to where one can inherit from a derived class,
thereby making this derived class the base class for the other new class.
As we can see in the diagram below C is derived class or child class of B and
and B is a child class of A.
Example
Multilevel
Inheritance:
Inheritance
3) Hierarchical Inheritance:
In such kind of inheritance one class is inherited by many sub classes.
As shown in the flow diagram class B,C and D inherits the same class A.
A is parent class (or base class) of B, C & D.
Example
Hierarchical
Inheritance:
Inheritance
4) Multiple Inheritance:
It refers to the concept of one class extending (Inherits) more than one base class.
The inheritance we learnt earlier had the concept of one base class or parent.
The problem with “multiple inheritance” is that the derived class will have to
manage the dependency on two base classes.
Most of the new OO languages like Small Talk, Java, C# do not support
Multiple inheritance.
Multiple Inheritance is supported in C++
Why it is not supported by java class ?
Inheritance class A{
void msg( ){
System.out.println("Hello");
}
}
class B{
void msg(){
System.out.println("Welcome");
}
}
class C extends A, B{ //suppose if it were
public static void main(String args[ ]){
C obj=new C( );
obj.msg( );
//Now which msg() method would be invoked ?
}
}
That is why Java class does not support multiple inheritance.
Inheritance Summary
Class C
Inheritance
But ?
We have noticed that multiple inheritances is not supported in java classes but it’s
supported in interfaces.
A single interface can extend multiple interfaces.
interface interface_name{
}
interface Bank{
abstract float rateOfInterest( );
}
class CBE implements Bank{
public float rateOfInterest( ) { return 7.1f; }
}
class Dashen implements Bank{
public float rateOfInterest( ) {return 7.5f; }
}
class Test{
public static void main(String[] args){
Bank cbe=new CBE ();
System.out.println("ROI: CBE "+ cbe.rateOfInterest( )); // 7.1
Bank dash=new Dashen ();
System.out.println("ROI: DASHEN "+ dash.rateOfInterest( )); //
7.5 }
Inheritance
The super Keyword
It is used inside a sub-class method definition to use data variable or to call a method
defined in the immediate parent class object.
Whenever we create the instance of subclass, an instance of parent class is created
implicitly i.e. referred by super reference variable.
Private methods of the super-class cannot be called, Only public and protected methods.
32
Polymorphism
class AA {
public void display( String c ) {
System.out.println(c);
}
public void display( int x, ) { //method overloading
System.out.println( x);
}
public static void main (String[] args) {
AA a = new AA( );
a. display( “Single”);
a. display( 102);
}
}
Polymorphism C . Different in Sequence of data type of arguments
class AA {
public void display( String name, int id ) {
System.out.println(name + “ , ”+ id);
}
public void display( int id, String name ) { //method overloading
System.out.println( id +” , ”+ name);
}
public static void main (String[] args) {
AA a = new AA( );
a. display( “Alemu” , 1200);
a. display( 1300 , “ Abebe”);
}
}
Polymorphism class AA {
public int display( int x, int y ) {
What will be the output ? return x+y;
}
public float display(int a, int b) {
return a+b;
}
public static void main (String[] args) {
AA a = new AA( );
int k= a. display(100 , 200)
System.out.println( k );
}
}
The first way is to use the new operator to create a new instance of an array:
String[] names = new String[3];
int numbers[]=new int[5];
The second way to create array by initializing the array contents
String names[]={“Alemu”,”Chala”,”Aster”};
int numbers[]={21,12,30,40,80};
49
ArrayList
The Java API provides several predefined data structures, called collections, used to store
groups of related objects.
These classes provide efficient methods that organize, store and retrieve your data without
requiring knowledge of how the data is being stored.
This reduces application-development time.
You’ve used arrays to store sequences of objects.
Arrays do not automatically change their size at execution time to accommodate additional
elements.
The collection class ArrayList<T> (from package java.util) provides a convenient
solution to this problem
it can dynamically change its size to accommodate more elements.
The T (by convention) is a placeholder
50
ArrayList (Cont…)
when declaring a new ArrayList, replace it with the type of elements that you want the
ArrayList to hold.
This is similar to specifying the type when declaring an array, except that only non primitive
types can be used with these collection classes.
For example, ArrayList< String > list; declares list as an ArrayList collection that can
store only String s.
Classes with this kind of placeholder that can be used with any type are called generic
classes.
// to create a new ArrayList of Strings with an initial capacity of 10
ArrayList< String > items = new ArrayList< String >();
51
Some methods and properties of class ArrayList<T>.
52
List
The java.util package provides the List interface for maintaining the ordered collection.
A List can contain the null and duplicate values.
The methods of the List are based on the index, so all the operations like insert, delete,
update, and search is based on the index.
ArrayList, LinkedList, Stack, and Vector are the implementation classes available in the
List interface.
In Java, we mostly used the ArrayList and LinkedList implementation classes to design a
list.
53
List Example
1.import java.util.*;
2.class ListExample{
3. public static void main(String args[]){
4. //Create List
5. List<String> names = new ArrayList<String>();
55
Set Example
1.import java.util.*;
2.public class SetExample{
3. public static void main(String[] args)
4. {
5. // creating HashSet implementation using the Set
6. Set<String> veg = new HashSet<String>();
7. veg.add("Ginger");
8. veg.add("Garlic");
9. veg.add("Onion");
10. veg.add("Ginger");
11. System.out.println(veg);
12. }
13.}
OUTPUT
[ Ginger , Garlic,
56
Onion ]
Exceptions Handling
57
Exceptions Handling
When an Exception occurs the normal flow of the program is disrupted and
application terminates abnormally, so exceptions are to be handled.
The exception handling in java is a mechanism to handle the runtime errors
so that normal flow of the application can be maintained.
An exception can occur for many different reasons:
A user has entered invalid data.
A file that needs to be opened cannot be found.
A network connection has been lost in the middle of communications or the
JVM has run out of memory. 58
Let's take a scenario:
•statement 1;
•statement 2; //exception occurs
•statement 3;
•statement 4;
Suppose there is 4 statements in our program and there occurs an exception at statement 2,
rest of the code will not be executed i.e. statement 3 & 4 will not run.
If we perform exception handling, rest of the statement will be executed.
59
public class C{
public static void main(String args[]){
int data=50/0; //may throw exception
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
60
Exception Hierarchy
61
Three categories of Exceptions
Checked exceptions (Compile time Exception :
A checked exception is an exception that occurs at the compile time, these are also called
as compile time exceptions. E.g FileReader class to read data from a file, if file not found
then an FileNotFoundException occurs.
Unchecked exceptions (Runtime Exception)
An Unchecked exception is an exception that occurs at the time of execution, these are also
called as Runtime Exceptions. these include programming bugs, such as logic errors or
improper use of an API. ArrayIndexOutOfBoundsException
Errors
These are not exceptions at all, but problems that arise beyond the control of the user.
For example, if a stack overflow occurs, 62
Checked exceptions
Exception Description
ClassNotFoundException Class not found.
CloneNotSupportedException Attempt to clone an object that does not implement the
Cloneable interface.
63
Unchecked exceptions
Exception Description
ArithmeticException Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException Array index is out-of-bounds.
ArrayStoreException Assignment to an array element of an incompatible type.
IllegalStateException Environment or application is in incorrect state.
IndexOutOfBoundsException Some type of index is out-of-bounds.
NegativeArraySizeException Array created with a negative size.
NullPointerException Invalid use of a null reference.
NumberFormatException Invalid conversion of a string to a numeric format.
StringIndexOutOfBounds Attempt to index outside the bounds of a string.
64
Handling Exceptions by using
try…… catch block
try…. catch …..finally block
throws for declaring the exception class
throw methods used to catch the exception
65
public class ExcepTest{
public static void main(String args[]){ int a[] = new int[2];
try{
System.out.println("Access element three :" + a[3]);
}
catch (ArrayIndexOutOfBoundsException e){
System.out.println("Exception thrown :" + e);
}finally{
a[0] = 6;
System.out.println("First element value: " +a[0]); System.out.println("The finally statement is
executed");
}
}
}
67
Throws example
class ThrowsExecp {
static void fun() throws IllegalAccessException {
System.out.println("Inside fun(). ");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
fun();
}
catch(IllegalAccessException e) {
System.out.println("caught in main.");
}
}
} 68
Multithread in java
69
Multithread in java
OS on single-processor computers create the illusion of concurrent execution by rapidly
switching between activities, but only a single instruction can execute at once.
In the classic programming model, there is a single CPU that reads instructions from
memory and carries them out, one after the other.
This is the only type of programming that we have considered so far ,and has limitations.
Modern computers have multiple processors, enables to perform several tasks at the same time.
To use the full potential of all those processors, we need to write programs that can do
parallel processing . These programs are threads.
In Java, a single task is called a thread which refers to a “thread of control” or “thread
of execution,” meaning a sequence of instructions that are executed one after another.70
Multithread in java
Concurrency Vs Parallelism
(a) multiple threads running on three CPUs (b) multiple threads share a single CPU
71
What is Multitasking?
Multitasking is a process of executing multiple tasks simultaneously to utilize the CPU.
Multitasking can be achieved in two ways:
Process-based Multitasking (Multiprocessing)
Each process has an address in memory (process allocated in a separate memory area).
A process is heavyweight and switching from one process to another requires time for
saving ,loading & registers
Thread-based Multitasking (Multithreading)
73
Multithread in java
Advantages of Java Multithreading
It improves concurrency and application responsiveness It improves program structure.
no need to wait for one thread to complete to start another.
Multiple threads share the same address and memory space or files simultaneously,
resources is reduced
Limitations of Java Multithreading
Writing code for multithreaded applications is challenging.
Their results cannot be easily predicted.
Finding the root cause of an error and debugging it becomes complex
Inefficient management of Concurrency and Parallelism may cause problems in the
application.
74
Multithread in java
Thread Life Cycle
A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then dies. The
following diagram shows the complete life cycle of a thread.
75
Multithread in java
Runnable − After a newly born thread is started, the thread becomes runnable
Running A runnable thread in this state is directly transit to running state (executing ).
Waiting/Blocked: The state when a thread has to wait. E.g.. for synchronization
Waiting can be Timed Waiting state for a specified interval of time.
Terminated (Dead) − A thread reaches the termination state because of the following
reasons
When a thread has finished its job, then it exists or terminates normally.
}
2. By implementing Runnable, interface.
}
77
Multithread in java
1. Creating thread using Thread class:
Thread is a java class, which
implements runnable interface
t1 then call
s the start(
method agai ) method a
n calls run( nd start
interface ) method of ru
nnable
79
Multithread in java
Commonly used methods of Thread class:
1. public void run(): is used to perform action for a thread.
2. public void start(): starts the execution of the thread. JVM calls the run() method
3. public void sleep(long miliseconds): Causes the currently executing thread to sleep
4. public void join(): waits for a thread to die.
5. public int getPriority(): returns the priority of the thread.
6. public int setPriority(int priority): changes the priority of the thread.
7. public boolean isAlive(): tests if the thread is alive.
8. public void yield(): causes the currently executing thread object to temporarily pause
9. public void suspend(): is used to suspend the thread.
10.public void resume(): is used to resume the suspended thread.
11.public void stop(): is used to stop the thread.
12.public void interrupt(): interrupts the thread.
80
Multithread in java
Thread Synchronization
• When multiple threads share an object and that object is modified by one or more of the
• If one thread is in the process of updating a shared object and another thread also tries
• Synchronization process of handling situations when two or more threads need access
to a shared resource
81
Multithread in java
Thread Synchronization…
• The problem can be solved by giving only one thread at a time exclusive access to code that
manipulates the shared object.
• When the thread with exclusive access to the object finishes manipulating it, one of the
waiting threads is allowed to proceed.
• This process, called thread synchronization, coordinates access to shared data by multiple
concurrent threads.
• Ensures that each thread accessing a shared object excludes all other threads from doing
so simultaneously—this is called mutual exclusion.
82
Thread without synchronization method
83
Thread with synchronization method
84
Multithread in java
Thread Priority
Each thread has a priority.
Priorities are represented by a number between 1 and 10.
In most cases, the thread scheduler schedules the threads according to their priority (known
as preemptive scheduling).
int getPriority(): method returns the priority of the given thread.
void setPriority(int priority): method updates or assign the priority of the thread to priority.
3 constants defined in Thread class:
1. public static int MIN_PRIORITY value is 1
2. public static int NORM_PRIORITY value is 5 (default)
3. public static int MAX_PRIORITY value is 10 85
public class Demo extends Thread{
public void run(){
System.out.println("Now, inside the run method"); }
public static void main(String[]args){
Demo my_thr_1 = new Demo();
Demo my_thr_2 = new Demo();
System.out.println("The thread priority of first thread is : " + my_thr_1.getPriority());
System.out.println("The thread priority of first thread is : " + my_thr_2.getPriority());
my_thr_1.setPriority(5); my_thr_2. setPriority(3);
System.out.println("The thread priority of first thread is : " + my_thr_1.getPriority());
System.out.println("The thread priority of first thread is : " + my_thr_2.getPriority());
System.out.print(Thread.currentThread().getName());
System.out.println("The thread priority of main thread is : " + Thread.currentThread().getPriority());
Thread.currentThread().setPriority(10);
System.out.println("The thread priority of main thread is : " +
Thread.currentThread().getPriority());
}
} 86
d”
E n
“
!
o u
k Y
a n
T h
87