1
Prepared by: Mr. Vipin Wani
Unit -3
2
Inheritance and Polymorphism
Exception Handling and Multithreading
By
Mr. Vipin Wani
Assistant Professor
MET BKC’ IoE, nashik
Prepared by: Mr. Vipin Wani
History
3
➢ Designed by Jems Gosling.
➢ Introduced in the year 1991.
➢ Initially Known as Oak.
➢ Renamed as Java in 1993.
➢ Projected by Sun Microsystems.
Prepared by: Mr. Vipin Wani
Introduction
4
➢Features of java
➢Java Program Execution
➢Java Execution Environment
➢JVM
Prepared by: Mr. Vipin Wani
Java Program Execution
5
Windows
Mac
Source Byte
Compile
Code Code
UNIX
Fig 1. Java Program Execution Process
Prepared by: Mr. Vipin Wani
Java Execution Environment
6
Java File Java Compiler .Class File
Class Loader
Java Runtime Byte Code
System Verifier
JVM
Native
OS
Fig 2. Java Program Execution Enviornment
Prepared by: Mr. Vipin Wani
Saving Java File
7
Saving Java File: Save a java File as ClassName.java
Is it Compulsory to save Java File as same name with Class Name?
Answer is NO,
When we save file and when we compile it then the compiler generates .class file with
the same name as class name, and remember always for compilation we use .java file and
for execution we use .class file. So if you want to save your program with different name
than your class name, then you just have to run your .class file which is generated after
compilation.
Prepared by: Mr. Vipin Wani
Inheritance
8
➢ It is the mechanism in java by which one class is allowed to inherit the
features(fields and methods) of another class.
➢ Important terminology:
1. Super Class: The class whose features are inherited is known as superclass (or a
base class or a parent class).
2. Sub Class: The class that inherits the other class is known as a subclass(or a
derived class, extended class, or child class).
3. Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to
create a new class and there is already a class that includes some of the code that
we want, we can derive our new class from the existing class. By doing this, we are
reusing the fields and methods of the existing class.
Prepared by: Mr. Vipin Wani
Types of Inheritance
9
1. Single Inheritance:
2. Multilevel Inheritance:
3. Hierarchical Inheritance:
4. Multiple Inheritance
5. Hybrid Inheritance
Prepared by: Mr. Vipin Wani
Types of Inheritance
10
1. Single Inheritance: In single inheritance, subclasses inherit the features of one
superclass. In the image below, class A serves as a base class for the derived class B.
Prepared by: Mr. Vipin Wani
Types of Inheritance
11
2. Multilevel Inheritance: In Multilevel Inheritance, a derived class will be inheriting a
base class and as well as the derived class also act as the base class to other class. In the
below image, class A serves as a base class for the derived class B, which in turn serves
as a base class for the derived class C.
Prepared by: Mr. Vipin Wani
Types of Inheritance
12
3. Hierarchical Inheritance: In Hierarchical Inheritance, one class serves as a
superclass (base class) for more than one subclass. In the below image, class A serves
as a base class for the derived class B, C and D.
Prepared by: Mr. Vipin Wani
Types of Inheritance
13
4. Multiple Inheritance: In Multiple inheritances, one class can have more than one
superclass and inherit features from all parent classes. Please note that Java
does not support multiple inheritances with classes. In java, we can achieve multiple
inheritances only through Interfaces. In the image below, Class C is derived from
interface A and B.
Prepared by: Mr. Vipin Wani
Types of Inheritance
14
5. Hybrid Inheritance: It is a mix of two or more of the above types of inheritance.
Since java doesn’t support multiple inheritances with classes, hybrid inheritance is also
not possible with classes. In java, we can achieve hybrid inheritance only through
Interfaces.
Prepared by: Mr. Vipin Wani
Example of Inheritance
15
class Super {
int x, y;
Super()
{
System.out.println(“In Default Constructor of Super Class");
x=10; y=50;
}
Super(int p, int q) {
System.out.println(“In Parametric Constructor of Super Class");
x=p;
y=q;
}}
Prepared by: Mr. Vipin Wani
Example of Inheritance
16
class Sub extends Super {
String b;
Sub() {
System.out.println(“In Default Constructor of Sub Class");
b="Welcome";
}
Sub(int c, int d, String q) {
super(c,d);
System.out.println(“In Parametric Constructor of Sub Class");
b=q;
}
public static void main(String[] arg) {
Sub s=new Sub();
System.out.println(" Values Using Default Constructor");
System.out.println("Value of X from Super is==>"+s.x);
System.out.println("Value of Y from Super is==>"+s.y);
System.out.println("Value of B from Super is==>"+s.b);
}}
Prepared by: Mr. Vipin Wani
Types of Relationship
17
1. “Is –A” Relationship
2. “Has –A” Relationship
Prepared by: Mr. Vipin Wani
Ways to achieve inheritance
18
There are only three ways to achieve inheritance:
1. Class Extends class (Single)
2. Class implements interface (multiple)
3. Interface extends interface (multiple)
Prepared by: Mr. Vipin Wani
Abstract Class
19
➢ A class which contains the abstract keyword in its declaration is known as abstract
class.
➢ Abstract classes may or may not contain abstract methods, i.e., methods without
body ( public void get(); )
➢ But, if a class has at least one abstract method, then the class must be declared
abstract.
➢ If a class is declared abstract, it cannot be instantiated.
➢ To use an abstract class, you have to inherit it from another class, provide
implementations to the abstract methods in it.
➢ If you inherit an abstract class, you have to provide implementations to all the
abstract methods in it.
Prepared by: Mr. Vipin Wani
Abstract Class
20
➢ Abstract Class Example:
abstract Class AbstarctDemo
{
static void display()
{
system.out.println(“Non Abstract Method in Abstrct Class”);
}
abstract void display2(); // Abstract method without body.
abstract void display3(); // Abstract method without body.
Prepared by: Mr. Vipin Wani
Interface
21
➢ An interface is a reference type in Java. It is similar to class. It is a collection of
abstract methods.
➢ A class implements an interface, thereby inheriting the abstract methods of the
interface.
➢ An interface is similar to a class in the following ways −
➢ An interface can contain any number of methods.
➢ An interface is written in a file with a .java extension, with the name of the interface
matching the name of the file.
➢ The byte code of an interface appears in a .class file.
➢ Interfaces appear in packages, and their corresponding bytecode file must be in a
directory structure that matches the package name.
Prepared by: Mr. Vipin Wani
Interface
22
Interface Example: to Demonstrate polymorphism
interface shape
{
public void drawShape();
}
Shape (Interface)
drawShape()
Circle (Class) Trangle (Class) Line (Class)
drawShape() drawShape() drawShape()
Prepared by: Mr. Vipin Wani
Abstract Class Vs Interface
23
Points Abstract Class Interface
Cannot be instantiated; contains both Specifies a set of methods a class must
Definition abstract (without implementation) and implement; methods are abstract by
concrete methods (with implementation) default.
Implementation Can have both implemented and abstract Methods are abstract by default; Java 8,
Method methods. can have default and static methods.
class can inherit from only one abstract
Inheritance A class can implement multiple interfaces.
class.
Methods and properties can have any
Methods and properties are implicitly
Access Modifiers access modifier (public, protected,
public.
private).
Can have member variables (final, non- Variables are implicitly public, static, and
Variables
final, static, non-static). final (constants).
Prepared by: Mr. Vipin Wani
Method Overloading
24
If a class has multiple methods having same name but different in parameters, it is
known as Method Overloading.
Overloading allows different methods to have the same name, but different signatures
where the signature can differ by the number of input parameters or type of input
parameters or both.
Overloading is related to compile-time (or static) polymorphism.
Prepared by: Mr. Vipin Wani
Method Overloading
25
public class Sum {
public int sum(int x, int y)
{
return (x + y);
}
public int sum(int x, float y, int z) {
return (x + y + z);
}
public static void main(String args[])
{
Sum s = new Sum();
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10, 20, 30));
}
Prepared by: Mr. Vipin Wani
Ways to Achieve Method Overloading
26
1.The number of parameters in two methods.
2.The data types of the parameters of methods.
3.The Order of the parameters of methods.
Prepared by: Mr. Vipin Wani
Method Overriding
27
Overriding is a feature that allows a subclass or child class to provide a specific
implementation of a method that is already provided by one of its super-classes or
parent classes.
When a method in a subclass has the same name, same parameters or signature, and
same return type(or sub-type) as a method in its super-class, then the method in the
subclass is said to override the method in the super-class.
Prepared by: Mr. Vipin Wani
Method Overriding
28
➢ Rules for Method Overriding
1. The argument list should be exactly the same as that of the overridden method.
2. The return type should be the same or a subtype of the return type declared in the
original overridden method in the superclass.
3. The access level cannot be more restrictive than the overridden method's access
level.
4. Instance methods can be overridden only if they are inherited by the subclass.
5. A method declared final cannot be overridden.
6. A method declared static cannot be overridden but can be re-declared.
7. If a method cannot be inherited, then it cannot be overridden.
Prepared by: Mr. Vipin Wani
Method Overriding
29
➢ Example of Method Overriding:
class Super{
public void add(int i, int j) {
System.out.println("Addition is="+(i+j));
}
}
class InherOverridEx extends InherOverrid {
public void add(int i, int j) {
System.out.println(" Addition is="+(i+j+j));
}
}
Prepared by: Mr. Vipin Wani
Access Specifiers
30
➢ The access modifiers in Java specifies the accessibility or scope of a field, method,
constructor, or class. We can change the access level of fields, constructors, methods,
and class by applying the access modifier on it.
Prepared by: Mr. Vipin Wani
Access Specifiers
31
1.Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
2.Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.
3.Protected: The access level of a protected modifier is within the package and outside
the package through child class. If you do not make the child class, it cannot be accessed
from outside the package.
4.Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.
Prepared by: Mr. Vipin Wani
Accessibility Using Various Access Specifiers
32
Access within class within package outside outside
Modifier package by package
subclass only
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
Prepared by: Mr. Vipin Wani
Access Specifiers Restriction Level
33
Prepared by: Mr. Vipin Wani
Exception Handling
34
➢ What is Exception?
➢ Handling the Exception
➢ Use of Try & Catch
➢ Use of Finally
Prepared by: Mr. Vipin Wani
Exception Handling
35
➢ Exception handling in Java allows developers to manage runtime errors
effectively by using mechanisms like try-catch block, finally block, throwing
Exceptions, Custom Exception handling, etc.
➢ An Exception is an unwanted or unexpected event that occurs because of logical
mistakes done by developer during the execution of a program, i.e., at runtime,
and disrupts the normal flow of the program's instructions.
➢ How to Handle Exceptions?
Prepared by: Mr. Vipin Wani
Exception Handling
36
➢ Exceptions can be handled with the help of following:
1. Try Block
2. Catch Block
3. Finally Block
4. Throw
5. Throws
Prepared by: Mr. Vipin Wani
Exception Handling
37
➢ Try & Catch Block:
➢ A try-catch block in Java is a mechanism to handle exception.
➢ The try block contains code that might thrown an exception.
➢ The catch block is used to handle the exceptions if it occurs.
try {
// Code that may throw an exception
}
catch (ExceptionType e) {
// Code to handle the exception
}
Prepared by: Mr. Vipin Wani
Exception Handling
38
➢ Finally Block:
➢ The finally block is used to execute important code regardless of whether an
exception occurs or not.
➢ finally block is always executes after the try-catch block. It is also used for
resource cleanup.
try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
}finally{
// cleanup code
}
Prepared by: Mr. Vipin Wani
Exception Handling
39
➢ Java throw
➢ The throw keyword in Java is used to explicitly throw an exception from a method or
any block of code. We can throw either checked or unchecked exception.
➢ The throw keyword is mainly used to throw custom exceptions.
➢ Example:
throw new IOException();
Prepared by: Mr. Vipin Wani
Exception Handling
40
➢ Java throws
➢ throws is a keyword in Java that is used in the signature of a method to indicate that
this method might throw one of the listed type exceptions.
➢ The caller to these methods has to handle the exception using a try-catch block.
➢ Example:
class ExceptionDemo {
public static void main(String[] args) throws Exception
{
System.out.println("Hello World!");
int c=10/0;
}}
Prepared by: Mr. Vipin Wani
Types of Exception
41
Prepared by: Mr. Vipin Wani
Types of Exception
42
1. Built-in Exception: Build-in Exception are pre-defined exception classes provided
by Java to handle common errors during program execution.
2. Checked Exceptions: Checked exceptions are called compile-time exceptions
because these exceptions are checked at compile-time weather they are handled or
not by the developer before compilation compiler. Ex. IOException, SQLException.
3. Unchecked Exceptions: The unchecked exceptions are just opposite to the checked
exceptions. The compiler will not check these exceptions are handled or not by the
developer at compile time. Ex. ArithmaticException
4: User-Defined Exception: Sometimes, the built-in exceptions in Java are not able to
describe a certain situation. In such cases, users can also create exceptions, which are
called "user-defined Exceptions
Prepared by: Mr. Vipin Wani
Multithreading
43
➢ Multithreading is a Java feature that allows the concurrent execution of two or
more parts of a program for maximum utilization of the CPU.
➢ Each part of such a program is called a thread. So, threads are lightweight
processes within a process.
➢ Different Ways to Create Threads
➢ Threads can be created by using two mechanisms:
1. Extending the Thread class
2. Implementing the Runnable Interface
Prepared by: Mr. Vipin Wani
Multithreading
44
1. By Extending the Thread Class
➢ We create a class that extends the java.lang.Thread class.
➢ This class overrides the run() method available in the Thread class.
➢ A thread begins its life inside the run() method.
➢ We create an object of our new class and call the start() method to start the
execution of a thread.start() invokes the run() method on the Thread object.
Prepared by: Mr. Vipin Wani
Multithreading Example (By Extending Thread class)
45
class Multithreading extends Thread {
public void run() {
try {
System.out.println("Thread " + Thread.currentThread().getId()
+ " is running"); }
catch (Exception e) { // Throwing an exception
System.out.println("Exception is caught"); }
}}
public class ThreadDemo {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
Multithreading object = new Multithreading();
object.start(); }
}}
Prepared by: Mr. Vipin Wani
Multithreading
46
2. By Implementing the Runnable interface
➢ We create a class that implements the java.lang.Runnable interface.
➢ This class overrides the run() method available in the Thread class.
➢ A thread begins its life inside the run() method.
➢ We create an object of our new class and call the start() method to start the
execution of a thread.start() invokes the run() method on the Thread object.
Prepared by: Mr. Vipin Wani
Multithreading Example (By Implementing Runnable Interface)
47
public class RunnableDemo implements Runnable {
public void run() {
System.out.println("Thread is Executing in run.....");
}
public static void main(String[] args) {
RunnableDemo ex = new RunnableDemo();
Thread t1= new Thread(ex);
t1.start();
System.out.println("Hi");
}
}
Prepared by: Mr. Vipin Wani
Thread Life Cycle
48
Born
Start()
Ready Block
Wait Notify()
I/O
Wait() Resume()
Sleep Running Suspend
Sleep(t) Destroy() Suspend()
Dead
Prepared by: Mr. Vipin Wani
Synchronization in Java
49
➢ In multithreading, synchronization is important to make sure multiple threads
safely work on shared resources.
➢ Without synchronization, data can become inconsistent or corrupted if multiple
threads access and modify shared variables at the same time.
➢ In Java, it is a mechanism that ensures that only one thread can access a
resource at any given time.
➢ This process helps prevent issues such as data inconsistency and race
conditions when multiple threads interact with shared resources
➢ The synchronized keyword can be applied to methods or blocks within methods.
➢ When a method or block is declared as synchronized, a lock is obtained on the
specified object, and other threads are blocked from accessing the synchronized
code until the lock is released.
Prepared by: Mr. Vipin Wani
Synchronization in Java
50
Synchronization Example:
public synchronized void aceessResources() {
System.out.println(“Single Thread accessing Resources Here”);
Prepared by: Mr. Vipin Wani
Practical Exposure
51
on
Object Oriented programming and
Computer Graphics Laboratory
PART-A
Prepared by: Mr. Vipin Wani
Assignment-1
52
Implement a robust Java calculator program that captures user input
dynamically, processes mathematical operations using conditional logic and
looping constructs, and ensures efficient error handling.
Methods to implement:
1. Using Command line Arguments
2. Using java.util.Scanner class
3. Using java.io.BufferedReader
4. Using Awt & JFrames
Prepared by: Mr. Vipin Wani
Assignment-1
53
Methods to implement:
1. Using Command line Arguments
class BesicDemo {
public static void main(String[] args)
{
String s;
System.out.println("Hello World!");
s=args[0];
int i=Integer.parseInt(args[1]);
int f=Integer.parseInt(args[2]);
System.out.println("The Value Of I==>"+i);
System.out.println("The Value Of F==>"+f);
System.out.println("The Value Of S==>"+s);
System.out.println("ddition of I & F is==>"+(i+f));
}
}
Prepared by: Mr. Vipin Wani
Assignment-1
54
Methods to implement:
2. Using java.util.Scanner class:
Syntax:
Scanner s= new Scanner(System.in);
System.out.println("Enter Input value for X as int:");
int x=s.nextInt();
Prepared by: Mr. Vipin Wani
Assignment-1
55
Methods to implement:
3. Using java.io.BufferedReader class:
Syntax:
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the value of Number1:");
Int n1=br.readLine();
Prepared by: Mr. Vipin Wani
Assignment-1
56
Methods to implement:
4. Using Awt & JFrames:
Prepared by: Mr. Vipin Wani
Assignment-2
57
Develop a Java program for an E-commerce order processing where some
products are initialized through multiple constructors, overloaded constructors,
where users can input some product details manually, the system computes total
order cost dynamically, applies discount policies based on conditions, and
presents a detailed invoice summarizing the purchase.
Methods to implement:
Use of ArrayList Class from java.util Packge
➢ Java ArrayList is a part of the collections framework and it is a class of java.util
package. It provides us with dynamic-sized arrays in Java.
➢ The main advantage of ArrayList is that, unlike normal arrays, we don't need to
mention the size when creating ArrayList. It automatically adjusts its capacity as
elements are added or removed.
➢ It may be slower than standard arrays, but it is helpful when the size is not known
in advance
Prepared by: Mr. Vipin Wani
Assignment-2
58
Syntax:
ArrayList<Integer> a = new ArrayList<Integer>();
// Adding Element in ArrayList
a.add(1);
a.add(2);
a.add(3);
// Printing ArrayList
System.out.println(a);
Prepared by: Mr. Vipin Wani
Assignment-3
59
Develop a Java program that implements a simple hotel room booking system
using twodimensional arrays. The system allows users to: View available and
booked rooms, Book a room by selecting a floor and room number and exit the
system when finished.
Methods to implement: Using 2D Boolean array 1st Dimension used for Floor and
2nd for Room
static final int FLOORS = 5; // Total number of floors
static final int ROOMS_PER_FLOOR = 5; // Total rooms per floor
static boolean[][] rooms = new boolean[FLOORS][ROOMS_PER_FLOOR];
Prepared by: Mr. Vipin Wani
Assignment-4
60
Create a Java program demonstrating single inheritance where a subclass
extends a superclass and calls its methods.
Methods to implement:
Create a Super Class with some attributes and extend the class in another class
implementing some additional attributes.
Prepared by: Mr. Vipin Wani
Assignment-5
61
Implement Multiple Inheritance using interface in Java to demonstrate
polymorphism.
Methods to implement:
Create a Super Class with some attributes and some interfaces with abstract methods
extend the class in another class also implement the interface to achieve
polymorphism
Prepared by: Mr. Vipin Wani
Assignment-6
62
Develop a Java program for simulation of any real time application with required
functionalities. For eg. ATM machine with functionalities like checking account
balance, withdrawing, and depositing money. Use try, catch, and finally blocks to
handle potential exceptions such as insufficient funds (throwing
ArithmeticException) and invalid input (throwing IllegalArgumentException).
Ensure that the application continues to run smoothly after handling exceptions.
Methods to implement:
Creating a menu Driven Program using switch case for various ATM operations such as
1. Deposit Money
2. Withdraw Money
3. Balance Enquiry
4. Mini Statement
Prepared by: Mr. Vipin Wani
Assignment-7
63
Create a multi-threaded Java application that simulates any real time
application with required functionalities. For eg. Basic chat system in which
each user (thread) sends and receives messages. Use isAlive() to check the status
of threads and join() to ensure proper synchronization. Implement thread
priorities to handle high-priority messages and demonstrate thread suspension,
resumption, and stopping..
Methods to implement:
1. Creating a Hardcoded user and messages to demonstrate live chat with
Multithreading
2. Creating applications using socket programming & Multithreading
Prepared by: Mr. Vipin Wani
Assignment-7
64
Methods to implement:
1. Creating a Hardcoded user and messages to demonstrate live chat with
Multithreading
String[] user1Msgs = {"Hi!", "How are you?", "That's great!"};
String[] user2Msgs = {"Hello!", "I'm fine.", "Let's meet."};
String[] user3Msgs = {"Hello!", "I'm Good.", "Yes Sure let's meet tomorrow."};
User user1 = new User("Anand", chatRoom, user1Msgs);
User user2 = new User("Kiran", chatRoom, user2Msgs);
User user3 = new User("Ganesh", chatRoom, user3Msgs);
Prepared by: Mr. Vipin Wani
Assignment-7
65
Methods to implement:
2. Creating applications using socket programming & Multithreading
➢ Use DatagramSocket class separately for Client & server program
➢ Connect with localhost to start communication
DatagramSocket cs = new DatagramSocket(5334);
InetAddress ip = InetAddress.getLocalHost();
Or
Socket s = new Socket(addr, port);
Prepared by: Mr. Vipin Wani
For any Suggestions or Query write to
[email protected]Download this PPT from following link.
https://wanivipin.wordpress.com/fops-fdps/
Prepared by: Mr. Vipin Wani 66