0% found this document useful (0 votes)
2 views

Module 2 Java

Module II covers key concepts in Java including inheritance, abstract classes, interfaces, exception handling, and multithreaded programming. It explains the benefits and types of inheritance, the use of abstract classes and interfaces, and the structure of exception handling in Java. Additionally, it discusses the Java thread model, thread lifecycle, synchronization, and inter-thread communication.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Module 2 Java

Module II covers key concepts in Java including inheritance, abstract classes, interfaces, exception handling, and multithreaded programming. It explains the benefits and types of inheritance, the use of abstract classes and interfaces, and the structure of exception handling in Java. Additionally, it discusses the Java thread model, thread lifecycle, synchronization, and inter-thread communication.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

📙 Module II: Inheritance, Abstract Classes and Interfaces, Exception

Handling and Multithreaded Programming ( By Santosh )


●​ Inheritance​

●​ Super class variables and subclass Objects​

●​ super reference​

●​ Constructor chaining​

●​ Method Overriding​

●​ final keyword​

●​ Abstract Classes and Interfaces​

○​ Abstract Classes​

○​ Abstract Methods​

○​ Defining Interface​

○​ Implementing Interface​

○​ Extending Interface​

○​ Interface References​

●​ Exception Handling​

○​ Hierarchy of Exception Classes​

○​ Types of Exception​

○​ Exception Classes​

○​ Uncaught Exceptions​

○​ Handling Exception​
○​ User-defined Exception​

●​ Multithreaded Programming​

○​ Java Thread Model​

○​ Runnable Interface​

○​ Thread Class​

○​ Thread Creation​

○​ Thread Life Cycle​

○​ Thread Scheduling​

○​ Synchronization and Deadlock​

○​ Inter-thread Communication​

○​ Joining Threads​

○​ Suspending, Resuming, and Stopping Threads​

📙 Module II: Inheritance, Abstract Classes and Interfaces, Exception Handling, and
Multithreaded Programming

📘 Inheritance in Java
Inheritance is one of the core concepts of Object-Oriented Programming (OOP). It allows one
class (called a subclass or derived class) to inherit fields and methods from another class
(called a superclass or base class). In simpler words, inheritance lets us create a new class
from an existing class so that we can reuse its code without rewriting it. This makes the program
more modular and easier to manage.

Key Benefits:

●​ Reduces code duplication by reusing existing code.​


●​ Helps in implementing polymorphism.​

●​ Makes code easier to maintain.​

●​ Encourages hierarchical classification.​

Types of Inheritance in Java:

●​ Single Inheritance – One class inherits from another.​

●​ Multilevel Inheritance – A class inherits from a class, which itself inherits from another
class.​

●​ Hierarchical Inheritance – Multiple classes inherit from the same superclass.​


(Note: Java does not support multiple inheritance with classes to avoid confusion, but it
supports it using interfaces.)​

Super Class Variables and Subclass Objects

In Java, a reference variable of a superclass can refer to an object of its subclass. This is called
upcasting and allows runtime polymorphism. It enables method calls to behave differently
based on the actual object type, even if the reference type is of the superclass.

Example:

class Animal {
void sound() {
System.out.println("Animal makes sound");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
}
Animal a = new Dog();
a.sound(); // Output: Dog barks

This is useful for writing flexible and scalable programs.


super Reference

The super keyword in Java is used to refer to the immediate parent class object. It is used in
the following ways:

●​ To access parent class methods.​

●​ To access parent class constructors.​

●​ To access parent class variables that are hidden.​

Example:

class Animal {
String color = "white";
}
class Dog extends Animal {
String color = "black";
void printColor() {
System.out.println(super.color); // prints white
}
}

super() is also used to call the parent class constructor explicitly.

Constructor Chaining

Constructor chaining is the process of calling one constructor from another in the same class or
from the superclass. This ensures all the constructors are executed in the correct order during
object creation.

●​ this() calls another constructor in the same class.​

●​ super() calls the constructor of the superclass.​

Example:

class A {
A() {
System.out.println("Constructor of A");
}
}
class B extends A {
B() {
super(); // calls constructor of A
System.out.println("Constructor of B");
}
}

Method Overriding

Method overriding means redefining a method of the superclass in a subclass. This is done to
provide specific behavior in the subclass.

Rules of Overriding:

●​ Same method name, return type, and parameters.​

●​ Cannot override final, static, or private methods.​

●​ Access modifier should not be more restrictive.​

Example:

class Animal {
void sound() {
System.out.println("Animal sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
}

final Keyword
The final keyword is used for constant declaration and to restrict inheritance or method
overriding.

●​ final variable: Value cannot be changed.​

●​ final method: Cannot be overridden.​

●​ final class: Cannot be subclassed.​

Example:

final int MAX = 100;


final class Animal {}
final void display() {}

final improves security and avoids unintentional changes.

🎯 Abstract Classes and Interfaces


Abstract Classes

An abstract class is a class that cannot be instantiated. It is used to define common behavior
and can have both abstract (no body) and non-abstract (with body) methods. It provides partial
abstraction.

Example:

abstract class Shape {


abstract void draw();
void show() {
System.out.println("Shape shown");
}
}

Used when classes share common traits but differ in behavior.

Abstract Methods
An abstract method has no body. Subclasses must override it to provide specific
implementation.

abstract void draw();

These enforce a contract that subclasses must follow.

Defining Interface

An interface in Java is a collection of abstract methods. From Java 8, interfaces can also
contain default and static methods. Interfaces support full abstraction and multiple
inheritance.

Example:

interface Drawable {
void draw();
default void msg() {
System.out.println("Default message");
}
}

Implementing Interface

A class uses the implements keyword to use an interface. It must override all abstract
methods of the interface.

Example:

class Circle implements Drawable {


public void draw() {
System.out.println("Drawing circle");
}
}

Extending Interface
One interface can inherit another using the extends keyword. This helps in organizing related
interfaces.

Example:

interface A {
void show();
}
interface B extends A {
void display();
}

Interface References

A reference of an interface type can hold the object of a class that implements the interface.
This helps in achieving polymorphism.

Example:

Drawable d = new Circle();


d.draw();

❗ Exception Handling
Hierarchy of Exception Classes

Java has a well-structured exception hierarchy:

●​ Throwable​

○​ Error (e.g., OutOfMemoryError)​

○​ Exception​

■​ Checked exceptions (e.g., IOException)​

■​ Unchecked exceptions (e.g., NullPointerException)​


Types of Exception

●​ Checked Exception – Checked at compile time. Must be handled.​

●​ Unchecked Exception – Occurs at runtime. Often programming errors.​

Examples:

●​ Checked: FileNotFoundException​

●​ Unchecked: ArithmeticException​

Exception Classes

Java provides many built-in exceptions like:

●​ ArithmeticException​

●​ ArrayIndexOutOfBoundsException​

●​ NullPointerException​

●​ IOException​

These help identify the type of problem that occurred during execution.

Uncaught Exceptions

If exceptions are not caught using try-catch, the program terminates abruptly. These are
called uncaught exceptions.

Handling Exception
Handled using try, catch, and finally blocks.

Example:

try {
int a = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
} finally {
System.out.println("Always executes");
}

User-defined Exception

You can create custom exceptions by extending the Exception class.

Example:

class MyException extends Exception {


MyException(String msg) {
super(msg);
}
}

Used to handle specific, custom error situations.

🔁 Multithreaded Programming
Java Thread Model

Java supports multithreading – the ability to execute multiple threads simultaneously. Each
thread is a lightweight sub-process, managed by the Java Virtual Machine.

Runnable Interface

Used to define the task for a thread. Implements run() method.


Example:

class MyRunnable implements Runnable {


public void run() {
System.out.println("Thread running");
}
}

Thread Class

Thread class provides methods to start, run, sleep, and control threads. Can be extended to
create a thread.

Example:

class MyThread extends Thread {


public void run() {
System.out.println("Thread started");
}
}

Thread Creation

Two ways to create threads:

●​ Extend Thread class.​

●​ Implement Runnable interface.​


Use start() method to begin execution.​

Thread Life Cycle

States of a thread:

●​ New – Created but not started.​

●​ Runnable – Ready to run.​


●​ Running – Actively executing.​

●​ Blocked/Waiting – Waiting for resources or signal.​

●​ Terminated – Finished execution.​

Thread Scheduling

Java uses priority-based thread scheduling. Thread priorities range from 1 (min) to 10 (max).

Use setPriority() and getPriority() methods to manage priorities.

Synchronization and Deadlock

Synchronization ensures only one thread accesses a resource at a time. Used to prevent race
conditions.

Example:

synchronized void printTable(int n) {


// Only one thread at a time can access this
}

Deadlock happens when two or more threads wait for each other forever.

Inter-thread Communication

Threads can communicate using:

●​ wait() – Thread waits.​

●​ notify() – Wakes one waiting thread.​

●​ notifyAll() – Wakes all waiting threads.​

Must be used within synchronized blocks.


Joining Threads

join() method ensures one thread waits for another to complete.

thread.join();

Used for sequential thread execution.

Suspending, Resuming, and Stopping Threads

Methods like suspend(), resume(), and stop() are deprecated due to unsafe behavior.​
Use a flag variable or interrupt() for safe thread control.

Example:

volatile boolean running = true;

Use this flag to control thread execution in a safe way.

You might also like