SlideShare a Scribd company logo
1 of 87
Department Information Technology
1
Advanced Programming
Tutorial
2
3
 OOP Concepts in java class  Abstraction  Inheritance
Object  Encapsulation  polymorphism
 Array and other collections Array  Array List
List Set
 Exceptions Handling  try….catch  try….catch…finally
throw …. throws
 Multithread in java

Tutorial Outlines
OOP Concepts in java
4
 Class
 Object
 Abstraction
 Encapsulation
 Inheritance
 Polymorphism
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.
 Abstraction provides us a generalized view of our classes or object by providing relevant
information.
 It is the process of hiding the working style of an object, and showing the information of
an object in understandable manner.
 Abstraction means putting all the variables and methods in a class, which are necessary
for all class members.
5
Abstraction (Cont.…)
 Real world Example of Abstraction: - Suppose we have an object Mobile Phone.
Suppose we have 3 mobile phones as following:-
Nokia 1400 (Features:- Calling, SMS)
Nokia 2700 (Features:- Calling, SMS, FM Radio, MP3, Camera)
Black Berry (Features:-Calling, SMS, FM Radio, MP3, Camera, Video Recording, Reading
E- mails)
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....)
public class Blackberry extends MobilePhone
{
public void FMRadio();
Public void MP3();
Public void Camera();
Public void FMRadio();
Public void Recording();
Public void ReadAndSendEmails();
}
abstract class MobilePhone
{
public void Calling();
public void SendSMS();
}
Public class Nokia1400 extends MobilePhone{
}
Public class Nokia2700 extends MobilePhone
{
public void FMRadio();
Public void MP3();
Public void Camera();
}
7
Encapsulation
Real world Example
Let's take example of Mobile Phone and Mobile Phone Manufacturer.
Suppose we are a Mobile Phone Manufacturer and we designed and developed a Mobile
Phone design(class),
now by using machinery we are manufacturing a Mobile Phone(object) for selling,
when we sell our Mobile Phone the user only learn how to use the Mobile Phone but not
that how this Mobile Phone works.
 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.
8
Difference Between Abstraction and Encapsulation
1. Abstraction solves the problem in the
design level.
1. Encapsulation solves the problem in
the implementation level.
2. Abstraction is used for hiding the
unwanted data and giving relevant data.
2. Encapsulation means hiding the code
and data into a single unit to protect the data
from outside world.
3. Abstraction lets focus on what the object
does instead of how it does it
3. Encapsulation means hiding the internal
details or mechanics of how an object does
something.
4. Abstraction- Outer layout, used in terms
of design.
For Example:-
Outer Look of a Mobile Phone, like it has a
display screen and keypad buttons to dial a
number.
4. Encapsulation- Inner layout, used in
terms of implementation.
For Example:- Inner Implementation detail
of a Mobile Phone, how keypad button and
Display Screen are connect with each other
using circuits.
Abstraction Encapsulation
9
10
Inheritance
Inheritance
 Inheritance is one of the key features of Object Oriented Programming.
 Inheritance allows a class to inherit property of another class.
 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
derived class from the base class.
 When a Class extends another class it inherits all non private data members
extends and implements keywords are used to describe inheritance in Java.
Inheritance
Inheritance
 If an app is developed using concept of inheritance, it will have following advantages
 Application development time is less.
 Application take less memory.
 Application execution time is less.
 Application performance is enhance (improved).
 Redundancy of the code is reduced ,so that we get consistence results and less
storage cost.
Inheritance
 Types of Inheritance
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance (Not supported by JAVA class)
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
Inheritance
Single Inheritance
with final class A
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.
Inheritance
Example
Multilevel
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.
Inheritance
Example
Hierarchical
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++
Inheritance
 Why it is not supported by java class ?
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
Inheritance
Summary
Class C
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.
 See an example on next slide
Inheritance
But ?
An interface in Java is a blueprint of a class.
It has static constants and abstract methods.
The interface in Java is a mechanism to achieve abstraction.
There can be only abstract methods in the Java interface, not method body.
It is used to achieve abstraction and multiple inheritance in Java.
interfaces
interface interface_name{
// Interface body usually abstract methods
}
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 }
}
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.
Usage of java super Keyword
1. It is used to differentiate the members of superclass from the members of subclass.
2. It is used to refer immediate parent class instance variable.
3. It is used to invoke immediate parent class constructor.
4. It is used to invoke immediate parent class method
Inheritance
class Automotive {
int speed = 150, produc_year = 2015;
}
class Vehicle extends Automotive {
int speed = 50;
}
class Bike4 extends Vehicle{
int speed =100;
public void display( ){
System.out.println( " The speed is " + super . speed); //will print speed of Vehicle now
}
public static void main (String args[ ]){
Bike4 b = new Bike4( );
b . display( );
System.out.println( b. produc_year);
}
}
Out put :
The speed is 50
2015
32
Polymorphism
Polymorphism
 Polymorphism is the ability of an object to take on many forms.
 It allows us to define one interface and have multiple implementations.
 Polymorphism can be elaborated as:
 An operation may exhibit different behavior in different instances.
 The behavior depends on the types of data used in the operation.
 It plays an important role in allowing objects having different internal structures to share the
same external interface.
 Polymorphism is extensively used in implementing inheritance.
Polymorphism class Fruit {
public void show( ) {
System.out.println("Fruit");
}
}
class Banana extends Fruit {
public void show( ) { //method overridden
System.out.println("Banana");
}
}
public class Application {
public static void main(String[] args) {
Fruit banana = new Banana( );
banana.show( );
}
}
Output
Banana
Polymorphism
Method Overloading (Compile-time Polymorphism or Static polymorphism)
Method Overriding (Runtime Polymorphism or Dynamic Polymorphism)
Types of Polymorphism in JAVA
Polymorphism
1. Method Overloading (Compile-time Polymorphism or Static polymorphism)
 In Java, it is possible to define two or more methods of same name in a class,
by provided their argument list or parameters are different.
 This concept is known as Method Overloading.
 Mostly methods should be in the same class.
Argument lists could differ in :
A) Number of parameters.
B) Data type of parameters.
C) Sequence of Data type of parameters
Polymorphism
class AA {
public void display( String c ) {
System.out.println(c);
}
public void display( String x, String y ) { //method overloading
System.out.println( x +” ”+y);
}
public static void main(String[] args) {
AA a = new AA( );
a. display( “Single”);
a. display( “First” , ”Second”);
}
}
A . Different Number of parameters in argument list
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);
}
}
B . Different in data type of arguments
Polymorphism
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”);
}
}
C . Different in Sequence of data type of arguments
Polymorphism class AA {
public int display( int x, int y ) {
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 );
}
}
What will be the output ?
 Since return type of method doesn’t matter while overloading a method.
Polymorphism
Rules for Method Overloading
1. Overloaded method should always be the part of the same class (can also
take place in sub class), with same name but different parameters.
2. Constructor in Java can be overloaded
3. Overloaded methods must have a different argument list.
4. The parameters may differ in their type or number, or in both.
5. They may have the same or different return types.
Polymorphism
2. Method Overriding (Runtime Polymorphism or Dynamic Polymorphism)
 Declaring a method in subclass which is already present in parent class is
known as method overriding.
 The benefit of overriding is:
 ability to define a behavior that's specific to the subclass type.
 subclass can implement a parent class method based on its requirement.
 In OO terms, overriding means to override the functionality of an existing method.
 For method overriding their must be an inheritance .
Polymorphism class Animal{
public void move( ){
System.out.println("Animals can move");
}
}
class Dog extends Animal{
public void move( ){
System.out.println("Dogs can walk and run");
}
}
public class TestDog{
public static void main (String args[ ] ){
Animal a = new Animal( ); // Animal reference and object
Animal b = new Dog( ); // Animal reference but Dog object
a.move( ); // runs the method in Animal class
b.move( ); //Runs the method in Dog class
}
}
class Animal{
public void move( ){
System.out.println("Animals can move");
}
}
class Dog extends Animal{
public void move( ){
System.out.println("Dogs can walk and run");
}
public void bark( ){
System.out.println("Dogs can bark");
}
public static void main (String args[ ] ){
Animal a = new Animal( ); // Animal reference and object
Animal b = new Dog( ); // Animal reference but Dog object
a.move( ); // runs the method in Animal class
b.move( ); //Runs the method in Dog class
b. bark( );
}
}
This would produce :
cannot find symbol :
method bark()
location: class Animal
b.bark();
^
Polymorphism
 Rules for Method Overriding:
1. Applies only to inherited methods
2. Object type (NOT reference variable type) determines which overridden method will be
used at runtime.
3. Overriding method can have different return type (if return types are not primitive) or
user defined return types( object types)
4. Static and final methods cannot be overridden
5. Constructors cannot be overridden
6. It is also known as Runtime polymorphism.
Polymorphism
Overriding with
different return type
Array and other collections
Arrays are a way to store a list of items.
Each element of the array holds an individual item, and we can place items into and
remove items from those slots as we need to.
Arrays can contain any type of value (base types or objects), but we can’t store different
types in a single array.
We can have an array of integers, or an array of strings, or array of characters
but we can’t have an array that contains, for example, both strings and integers.
 To create an array in Java, we use three steps:
1. Declare a variable to hold the array.
2. Create a new array object and assign it to the array variable.
3. Store things in that array.
Eg String name[ ]; or String [ ] name ;
int numbers[ ]; or int[ ] numbers;
Array in java
48
Creating Array Objects
The second step is to create an array object and assign it to that variable. There are two
ways to do this:
• Using new
• Directly initializing the contents of that array
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
50
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
ArrayList
51
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 >();
ArrayList (Cont…)
52
Some methods and properties of class ArrayList<T>.
53
 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.
List
54
1.import java.util.*;
2.class ListExample{
3. public static void main(String args[]){
4. //Create List
5. List<String> names = new ArrayList<String>();
6. //Adding elements in the List.
7. names.add(“Abebe");
8. names.add(“Alemu");
9. names.add(“Chala");
10. names.add(“Abdi");
11. //Performing iteration of list to print each element of it.
12. for(String name: names)
13. System.out.println(name);
14. }
15.}
List Example
55
 The set is an interface available in the java.util package.
 The set interface extends the Collection interface.
 An unordered collection or list in which duplicates are not allowed is referred to as
a collection interface.
 The set interface is used to create the mathematical set.
 The set interface use collection interface's methods to avoid the insertion of the same
elements.
 SortedSet and NavigableSet are two interfaces that extend the set implementation.
Set
56
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, Onion ]
Set Example
57
Exceptions Handling
58
 Exception (exceptional event) is a problem happens during the execution of a program.
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.
Exceptions Handling
59
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.
60
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
 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
63
IllegalAccessException Access to a class is denied.
InstantiationException Attempt to create an object of an abstract class or interface.
InterruptedException One thread has been interrupted by another thread.
NoSuchFieldException A requested field does not exist.
NoSuchMethodException A requested method does not exist.
Exception Description
ClassNotFoundException Class not found.
CloneNotSupportedException Attempt to clone an object that does not implement the
Cloneable interface.
Checked exceptions
64
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.
Unchecked exceptions
65
 Handling Exceptions by using
 try…… catch block
 try…. catch …..finally block
 throws for declaring the exception class
 throw methods used to catch the exception
66
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");
}
}
}
This would produce the following result:
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3 First element value: 6
The finally statement is executed
67
Note the following:
 A catch clause cannot exist without a try statement.
 It is not compulsory to have finally clauses whenever a try/catch block is present.
 The try block cannot be present without either catch clause or finally clause.
 Any code cannot be present in between the try, catch, finally blocks.
 For each try block there can be zero or more catch blocks, but only one finally block.
 If you don't handle exception, before terminating the program, JVM executes finally
block(if any).
 The finally block will not be executed if program exits (either by calling System.exit() or
by causing a fatal error that causes the process to abort).
68
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.");
}
}
}
69
Multithread in java
70
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.
 Multithread in java
71
 Concurrency Vs Parallelism
Concurrency is about executing/managing multiple instruction/tasks sequences at the
same time on a single CPU.
 parallelism is running/managing multiple instruction sequences at the same time on
multiple CPUs.
 Multithread in java
(a) multiple threads running on three CPUs (b) multiple threads share a single CPU
72
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)
 Threads share the same address space (memory).
 A thread is a light-weight and smallest part of a process that can run concurrently with
the other parts (threads) of the same process
 The process of executing multiple threads simultaneously is known as multithreading.
73
Threads are independent. If there occurs exception in one thread, it does not affect other
threads.
 Multithread in java
74
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.
 Multithread in java
75
 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.
76
 Multithread in java
The various stages of life cycle of thread are
 New/born thread. − it begins its life cycle in the new state until the program starts the thread.
 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.
 Abnormal termination: It occurs when some unusual events/ faults occur.
77
 How to create a thread in Java?
There are commonly two ways to create a thread:
1. By extending Thread class
class A extends Thread{
}
2. By implementing Runnable, interface.
class A implements Runnable{
}
 Multithread in java
78
 Multithread in java
1. Creating thread using Thread class:
Thread is a java class, which
implements runnable interface
run() is a method for runnable
interface
start() is a method for Thread
class which calls run( ) method
t1 is a an object of Thread1 (user
defined class) can inherit Thread
properties
79
1. Creating a Thread by implementing Runnable interface
 Multithread in java
mt a object for Thread2
class
t1 is Object for Java Thread
And instantiated by Thread2 object
mt as runnable object
80
 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.
 Multithread in java
 Thread Synchronization
• When multiple threads share an object and that object is modified by one or more of
the threads, indeterminate results may occur.
• If one thread is in the process of updating a shared object and another thread also tries
to update it, it is unclear which thread’s update takes effect.
• Synchronization process of handling situations when two or more threads need
access to a shared resource
81
 Multithread in java
82
• 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.
 Multithread in java
 Thread Synchronization…
83
When t1 and t2 are executed the increament
method, they are not informed on from the other,
e.g 1 is missed, and 2 is written twice. They
share the same method and they are in race
condition (one cannot wait until the other
finishes.
Thread without synchronization method
84
This method makes the thread to wait until
the resource is released by the other thread.
Thread with synchronization method
85
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
 Multithread in java
86
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());
}
}
87

More Related Content

Similar to ITTutor Advanced Java (1).pptx

Understanding And Using Reflection
Understanding And Using ReflectionUnderstanding And Using Reflection
Understanding And Using ReflectionGanesh Samarthyam
 
Inheritance in OOPs with java
Inheritance in OOPs with javaInheritance in OOPs with java
Inheritance in OOPs with javaAAKANKSHA JAIN
 
Object+oriented+programming+in+java
Object+oriented+programming+in+javaObject+oriented+programming+in+java
Object+oriented+programming+in+javaYe Win
 
Intro Java Rev010
Intro Java Rev010Intro Java Rev010
Intro Java Rev010Rich Helton
 
Introduction to object oriented programming concepts
Introduction to object oriented programming conceptsIntroduction to object oriented programming concepts
Introduction to object oriented programming conceptsGanesh Karthik
 
OOP in Java Presentation.pptx
OOP in Java Presentation.pptxOOP in Java Presentation.pptx
OOP in Java Presentation.pptxmrxyz19
 
Fundamentals of oops in .Net
Fundamentals of oops in .NetFundamentals of oops in .Net
Fundamentals of oops in .NetHarman Bajwa
 
Object Oriented Programming With Real-World Scenario
Object Oriented Programming With Real-World ScenarioObject Oriented Programming With Real-World Scenario
Object Oriented Programming With Real-World ScenarioDurgesh Singh
 
INDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptx
INDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptxINDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptx
INDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptxIndu65
 
21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)ssuser7f90ae
 
C#.net interview questions for dynamics 365 ce crm developers
C#.net interview questions for dynamics 365 ce crm developersC#.net interview questions for dynamics 365 ce crm developers
C#.net interview questions for dynamics 365 ce crm developersSanjaya Prakash Pradhan
 
Selenium Training .pptx
Selenium Training .pptxSelenium Training .pptx
Selenium Training .pptxSajidTk2
 
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptxSodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptxRudranilDas11
 
Exception handling and packages.pdf
Exception handling and packages.pdfException handling and packages.pdf
Exception handling and packages.pdfKp Sharma
 
Chapter 04 object oriented programming
Chapter 04 object oriented programmingChapter 04 object oriented programming
Chapter 04 object oriented programmingPraveen M Jigajinni
 

Similar to ITTutor Advanced Java (1).pptx (20)

Understanding And Using Reflection
Understanding And Using ReflectionUnderstanding And Using Reflection
Understanding And Using Reflection
 
Opp concept in c++
Opp concept in c++Opp concept in c++
Opp concept in c++
 
Inheritance in OOPs with java
Inheritance in OOPs with javaInheritance in OOPs with java
Inheritance in OOPs with java
 
Object+oriented+programming+in+java
Object+oriented+programming+in+javaObject+oriented+programming+in+java
Object+oriented+programming+in+java
 
Intro Java Rev010
Intro Java Rev010Intro Java Rev010
Intro Java Rev010
 
Introduction to object oriented programming concepts
Introduction to object oriented programming conceptsIntroduction to object oriented programming concepts
Introduction to object oriented programming concepts
 
Java oop concepts
Java oop conceptsJava oop concepts
Java oop concepts
 
OOP in Java Presentation.pptx
OOP in Java Presentation.pptxOOP in Java Presentation.pptx
OOP in Java Presentation.pptx
 
Fundamentals of oops in .Net
Fundamentals of oops in .NetFundamentals of oops in .Net
Fundamentals of oops in .Net
 
Lecture 12
Lecture 12Lecture 12
Lecture 12
 
Object Oriented Programming With Real-World Scenario
Object Oriented Programming With Real-World ScenarioObject Oriented Programming With Real-World Scenario
Object Oriented Programming With Real-World Scenario
 
INDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptx
INDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptxINDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptx
INDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptx
 
Java_notes.ppt
Java_notes.pptJava_notes.ppt
Java_notes.ppt
 
Core_Java_Interview.pdf
Core_Java_Interview.pdfCore_Java_Interview.pdf
Core_Java_Interview.pdf
 
21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)
 
C#.net interview questions for dynamics 365 ce crm developers
C#.net interview questions for dynamics 365 ce crm developersC#.net interview questions for dynamics 365 ce crm developers
C#.net interview questions for dynamics 365 ce crm developers
 
Selenium Training .pptx
Selenium Training .pptxSelenium Training .pptx
Selenium Training .pptx
 
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptxSodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
 
Exception handling and packages.pdf
Exception handling and packages.pdfException handling and packages.pdf
Exception handling and packages.pdf
 
Chapter 04 object oriented programming
Chapter 04 object oriented programmingChapter 04 object oriented programming
Chapter 04 object oriented programming
 

Recently uploaded

"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 

Recently uploaded (20)

"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 

ITTutor Advanced Java (1).pptx

  • 3. 3  OOP Concepts in java class  Abstraction  Inheritance Object  Encapsulation  polymorphism  Array and other collections Array  Array List List Set  Exceptions Handling  try….catch  try….catch…finally throw …. throws  Multithread in java  Tutorial Outlines
  • 4. OOP Concepts in java 4  Class  Object  Abstraction  Encapsulation  Inheritance  Polymorphism
  • 5. 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.  Abstraction provides us a generalized view of our classes or object by providing relevant information.  It is the process of hiding the working style of an object, and showing the information of an object in understandable manner.  Abstraction means putting all the variables and methods in a class, which are necessary for all class members. 5
  • 6. Abstraction (Cont.…)  Real world Example of Abstraction: - Suppose we have an object Mobile Phone. Suppose we have 3 mobile phones as following:- Nokia 1400 (Features:- Calling, SMS) Nokia 2700 (Features:- Calling, SMS, FM Radio, MP3, Camera) Black Berry (Features:-Calling, SMS, FM Radio, MP3, Camera, Video Recording, Reading E- mails) 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
  • 7. Abstraction(Cont....) public class Blackberry extends MobilePhone { public void FMRadio(); Public void MP3(); Public void Camera(); Public void FMRadio(); Public void Recording(); Public void ReadAndSendEmails(); } abstract class MobilePhone { public void Calling(); public void SendSMS(); } Public class Nokia1400 extends MobilePhone{ } Public class Nokia2700 extends MobilePhone { public void FMRadio(); Public void MP3(); Public void Camera(); } 7
  • 8. Encapsulation Real world Example Let's take example of Mobile Phone and Mobile Phone Manufacturer. Suppose we are a Mobile Phone Manufacturer and we designed and developed a Mobile Phone design(class), now by using machinery we are manufacturing a Mobile Phone(object) for selling, when we sell our Mobile Phone the user only learn how to use the Mobile Phone but not that how this Mobile Phone works.  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. 8
  • 9. Difference Between Abstraction and Encapsulation 1. Abstraction solves the problem in the design level. 1. Encapsulation solves the problem in the implementation level. 2. Abstraction is used for hiding the unwanted data and giving relevant data. 2. Encapsulation means hiding the code and data into a single unit to protect the data from outside world. 3. Abstraction lets focus on what the object does instead of how it does it 3. Encapsulation means hiding the internal details or mechanics of how an object does something. 4. Abstraction- Outer layout, used in terms of design. For Example:- Outer Look of a Mobile Phone, like it has a display screen and keypad buttons to dial a number. 4. Encapsulation- Inner layout, used in terms of implementation. For Example:- Inner Implementation detail of a Mobile Phone, how keypad button and Display Screen are connect with each other using circuits. Abstraction Encapsulation 9
  • 11. Inheritance  Inheritance is one of the key features of Object Oriented Programming.  Inheritance allows a class to inherit property of another class.  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 derived class from the base class.  When a Class extends another class it inherits all non private data members
  • 12. extends and implements keywords are used to describe inheritance in Java. Inheritance
  • 14.  If an app is developed using concept of inheritance, it will have following advantages  Application development time is less.  Application take less memory.  Application execution time is less.  Application performance is enhance (improved).  Redundancy of the code is reduced ,so that we get consistence results and less storage cost. Inheritance
  • 15.  Types of Inheritance 1. Single Inheritance 2. Multilevel Inheritance 3. Hierarchical Inheritance 4. Multiple Inheritance (Not supported by JAVA class) Inheritance
  • 16. 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
  • 17. Single Inheritance example program in Java Inheritance
  • 19. 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. Inheritance
  • 21. 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. Inheritance
  • 23. 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++ Inheritance  Why it is not supported by java class ?
  • 24. 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
  • 26. 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.  See an example on next slide Inheritance But ?
  • 27. An interface in Java is a blueprint of a class. It has static constants and abstract methods. The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in the Java interface, not method body. It is used to achieve abstraction and multiple inheritance in Java. interfaces interface interface_name{ // Interface body usually abstract methods }
  • 28. 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 } }
  • 29.
  • 30. 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. Usage of java super Keyword 1. It is used to differentiate the members of superclass from the members of subclass. 2. It is used to refer immediate parent class instance variable. 3. It is used to invoke immediate parent class constructor. 4. It is used to invoke immediate parent class method Inheritance
  • 31. class Automotive { int speed = 150, produc_year = 2015; } class Vehicle extends Automotive { int speed = 50; } class Bike4 extends Vehicle{ int speed =100; public void display( ){ System.out.println( " The speed is " + super . speed); //will print speed of Vehicle now } public static void main (String args[ ]){ Bike4 b = new Bike4( ); b . display( ); System.out.println( b. produc_year); } } Out put : The speed is 50 2015
  • 33. Polymorphism  Polymorphism is the ability of an object to take on many forms.  It allows us to define one interface and have multiple implementations.  Polymorphism can be elaborated as:  An operation may exhibit different behavior in different instances.  The behavior depends on the types of data used in the operation.  It plays an important role in allowing objects having different internal structures to share the same external interface.  Polymorphism is extensively used in implementing inheritance.
  • 34. Polymorphism class Fruit { public void show( ) { System.out.println("Fruit"); } } class Banana extends Fruit { public void show( ) { //method overridden System.out.println("Banana"); } } public class Application { public static void main(String[] args) { Fruit banana = new Banana( ); banana.show( ); } } Output Banana
  • 35. Polymorphism Method Overloading (Compile-time Polymorphism or Static polymorphism) Method Overriding (Runtime Polymorphism or Dynamic Polymorphism) Types of Polymorphism in JAVA
  • 36. Polymorphism 1. Method Overloading (Compile-time Polymorphism or Static polymorphism)  In Java, it is possible to define two or more methods of same name in a class, by provided their argument list or parameters are different.  This concept is known as Method Overloading.  Mostly methods should be in the same class. Argument lists could differ in : A) Number of parameters. B) Data type of parameters. C) Sequence of Data type of parameters
  • 37. Polymorphism class AA { public void display( String c ) { System.out.println(c); } public void display( String x, String y ) { //method overloading System.out.println( x +” ”+y); } public static void main(String[] args) { AA a = new AA( ); a. display( “Single”); a. display( “First” , ”Second”); } } A . Different Number of parameters in argument list
  • 38. 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); } } B . Different in data type of arguments
  • 39. Polymorphism 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”); } } C . Different in Sequence of data type of arguments
  • 40. Polymorphism class AA { public int display( int x, int y ) { 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 ); } } What will be the output ?  Since return type of method doesn’t matter while overloading a method.
  • 41. Polymorphism Rules for Method Overloading 1. Overloaded method should always be the part of the same class (can also take place in sub class), with same name but different parameters. 2. Constructor in Java can be overloaded 3. Overloaded methods must have a different argument list. 4. The parameters may differ in their type or number, or in both. 5. They may have the same or different return types.
  • 42. Polymorphism 2. Method Overriding (Runtime Polymorphism or Dynamic Polymorphism)  Declaring a method in subclass which is already present in parent class is known as method overriding.  The benefit of overriding is:  ability to define a behavior that's specific to the subclass type.  subclass can implement a parent class method based on its requirement.  In OO terms, overriding means to override the functionality of an existing method.  For method overriding their must be an inheritance .
  • 43. Polymorphism class Animal{ public void move( ){ System.out.println("Animals can move"); } } class Dog extends Animal{ public void move( ){ System.out.println("Dogs can walk and run"); } } public class TestDog{ public static void main (String args[ ] ){ Animal a = new Animal( ); // Animal reference and object Animal b = new Dog( ); // Animal reference but Dog object a.move( ); // runs the method in Animal class b.move( ); //Runs the method in Dog class } }
  • 44. class Animal{ public void move( ){ System.out.println("Animals can move"); } } class Dog extends Animal{ public void move( ){ System.out.println("Dogs can walk and run"); } public void bark( ){ System.out.println("Dogs can bark"); } public static void main (String args[ ] ){ Animal a = new Animal( ); // Animal reference and object Animal b = new Dog( ); // Animal reference but Dog object a.move( ); // runs the method in Animal class b.move( ); //Runs the method in Dog class b. bark( ); } } This would produce : cannot find symbol : method bark() location: class Animal b.bark(); ^ Polymorphism
  • 45.  Rules for Method Overriding: 1. Applies only to inherited methods 2. Object type (NOT reference variable type) determines which overridden method will be used at runtime. 3. Overriding method can have different return type (if return types are not primitive) or user defined return types( object types) 4. Static and final methods cannot be overridden 5. Constructors cannot be overridden 6. It is also known as Runtime polymorphism. Polymorphism
  • 47. Array and other collections
  • 48. Arrays are a way to store a list of items. Each element of the array holds an individual item, and we can place items into and remove items from those slots as we need to. Arrays can contain any type of value (base types or objects), but we can’t store different types in a single array. We can have an array of integers, or an array of strings, or array of characters but we can’t have an array that contains, for example, both strings and integers.  To create an array in Java, we use three steps: 1. Declare a variable to hold the array. 2. Create a new array object and assign it to the array variable. 3. Store things in that array. Eg String name[ ]; or String [ ] name ; int numbers[ ]; or int[ ] numbers; Array in java 48
  • 49. Creating Array Objects The second step is to create an array object and assign it to that variable. There are two ways to do this: • Using new • Directly initializing the contents of that array 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
  • 50. 50 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 ArrayList
  • 51. 51 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 >(); ArrayList (Cont…)
  • 52. 52 Some methods and properties of class ArrayList<T>.
  • 53. 53  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. List
  • 54. 54 1.import java.util.*; 2.class ListExample{ 3. public static void main(String args[]){ 4. //Create List 5. List<String> names = new ArrayList<String>(); 6. //Adding elements in the List. 7. names.add(“Abebe"); 8. names.add(“Alemu"); 9. names.add(“Chala"); 10. names.add(“Abdi"); 11. //Performing iteration of list to print each element of it. 12. for(String name: names) 13. System.out.println(name); 14. } 15.} List Example
  • 55. 55  The set is an interface available in the java.util package.  The set interface extends the Collection interface.  An unordered collection or list in which duplicates are not allowed is referred to as a collection interface.  The set interface is used to create the mathematical set.  The set interface use collection interface's methods to avoid the insertion of the same elements.  SortedSet and NavigableSet are two interfaces that extend the set implementation. Set
  • 56. 56 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, Onion ] Set Example
  • 58. 58  Exception (exceptional event) is a problem happens during the execution of a program. 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. Exceptions Handling
  • 59. 59 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.
  • 60. 60 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
  • 62. 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
  • 63. 63 IllegalAccessException Access to a class is denied. InstantiationException Attempt to create an object of an abstract class or interface. InterruptedException One thread has been interrupted by another thread. NoSuchFieldException A requested field does not exist. NoSuchMethodException A requested method does not exist. Exception Description ClassNotFoundException Class not found. CloneNotSupportedException Attempt to clone an object that does not implement the Cloneable interface. Checked exceptions
  • 64. 64 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. Unchecked exceptions
  • 65. 65  Handling Exceptions by using  try…… catch block  try…. catch …..finally block  throws for declaring the exception class  throw methods used to catch the exception
  • 66. 66 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"); } } } This would produce the following result: Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3 First element value: 6 The finally statement is executed
  • 67. 67 Note the following:  A catch clause cannot exist without a try statement.  It is not compulsory to have finally clauses whenever a try/catch block is present.  The try block cannot be present without either catch clause or finally clause.  Any code cannot be present in between the try, catch, finally blocks.  For each try block there can be zero or more catch blocks, but only one finally block.  If you don't handle exception, before terminating the program, JVM executes finally block(if any).  The finally block will not be executed if program exits (either by calling System.exit() or by causing a fatal error that causes the process to abort).
  • 68. 68 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."); } } }
  • 70. 70 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.  Multithread in java
  • 71. 71  Concurrency Vs Parallelism Concurrency is about executing/managing multiple instruction/tasks sequences at the same time on a single CPU.  parallelism is running/managing multiple instruction sequences at the same time on multiple CPUs.  Multithread in java (a) multiple threads running on three CPUs (b) multiple threads share a single CPU
  • 72. 72 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)  Threads share the same address space (memory).  A thread is a light-weight and smallest part of a process that can run concurrently with the other parts (threads) of the same process  The process of executing multiple threads simultaneously is known as multithreading.
  • 73. 73 Threads are independent. If there occurs exception in one thread, it does not affect other threads.  Multithread in java
  • 74. 74 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.  Multithread in java
  • 75. 75  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.
  • 76. 76  Multithread in java The various stages of life cycle of thread are  New/born thread. − it begins its life cycle in the new state until the program starts the thread.  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.  Abnormal termination: It occurs when some unusual events/ faults occur.
  • 77. 77  How to create a thread in Java? There are commonly two ways to create a thread: 1. By extending Thread class class A extends Thread{ } 2. By implementing Runnable, interface. class A implements Runnable{ }  Multithread in java
  • 78. 78  Multithread in java 1. Creating thread using Thread class: Thread is a java class, which implements runnable interface run() is a method for runnable interface start() is a method for Thread class which calls run( ) method t1 is a an object of Thread1 (user defined class) can inherit Thread properties
  • 79. 79 1. Creating a Thread by implementing Runnable interface  Multithread in java mt a object for Thread2 class t1 is Object for Java Thread And instantiated by Thread2 object mt as runnable object
  • 80. 80  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.  Multithread in java
  • 81.  Thread Synchronization • When multiple threads share an object and that object is modified by one or more of the threads, indeterminate results may occur. • If one thread is in the process of updating a shared object and another thread also tries to update it, it is unclear which thread’s update takes effect. • Synchronization process of handling situations when two or more threads need access to a shared resource 81  Multithread in java
  • 82. 82 • 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.  Multithread in java  Thread Synchronization…
  • 83. 83 When t1 and t2 are executed the increament method, they are not informed on from the other, e.g 1 is missed, and 2 is written twice. They share the same method and they are in race condition (one cannot wait until the other finishes. Thread without synchronization method
  • 84. 84 This method makes the thread to wait until the resource is released by the other thread. Thread with synchronization method
  • 85. 85 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  Multithread in java
  • 86. 86 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()); } }
  • 87. 87