UNIT III- INTERFACES AND MULTIPLE INHERITANCE
What is an Interface?
An interface in Java is a reference type that can contain only abstract methods, constants,
default methods, static methods, and nested types.
It defines a contract that a class must fulfill by implementing the interface.
Syntax
java
Copy code
interface InterfaceName {
// Abstract methods
void method1();
void method2();
}
Why Use Interfaces?
1. To achieve multiple inheritance (not possible with classes due to ambiguity issues).
2. To establish a standard for unrelated classes to implement.
Example
java
Copy code
interface Animal {
void sound();
}
interface Pet {
void play();
}
class Dog implements Animal, Pet {
@Override
public void sound() {
System.out.println("Dog barks");
}
@Override
public void play() {
System.out.println("Dog plays fetch");
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.sound();
myDog.play();
}
}
Multiple Inheritance Using Interfaces
Java does not support multiple inheritance with classes to avoid the "Diamond Problem."
Interfaces allow multiple inheritance without ambiguity.
java
Copy code
interface A {
void showA();
}
interface B {
void showB();
}
class C implements A, B {
public void showA() {
System.out.println("Method from Interface A");
}
public void showB() {
System.out.println("Method from Interface B");
}
}
public class Main {
public static void main(String[] args) {
C obj = new C();
obj.showA();
obj.showB();
}
}
PACKAGES: PUTTING CLASSES TOGETHER
What is a Package?
A package is a namespace for organizing classes and interfaces.
Helps to:
1. Avoid name conflicts.
2. Make code modular and easier to maintain.
Creating a Package
1. Use the package keyword.
2. Save the file in a directory matching the package name.
java
Copy code
// Save as MyPackage/MyClass.java
package MyPackage;
public class MyClass {
public void display() {
System.out.println("Hello from MyPackage!");
}
}
Using a Package
Use import to access classes from a package.
java
Copy code
import MyPackage.MyClass;
public class Main {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.display();
}
}
MULTITHREADED PROGRAMMING
What is Multithreading?
Multithreading is a process of executing multiple threads simultaneously to improve
application performance.
Creating a Threads
There are two ways to create a thread.
It can be created by extending the Thread class and overriding its run() method:
1. Extending the Thread Class
Override the run() method and call start().
java
Copy code
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running...");
}
}
public class Main {
public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start();
}
}
2. Implementing the Runnable Interface
Implement the Runnable interface and pass it to a Thread object.
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread running using Runnable interface");
}
}
public class Main {
public static void main(String[] args) {
MyRunnable r = new MyRunnable();
Thread t = new Thread(r);
t.start();
}
}
Life cycle of a Thread
The life cycle of a thread in Java refers to the various states of a
thread goes through. For example, a thread is born, started, runs,
and then dies. Thread class defines the life cycle and various states
of a thread.
Flow Chart of Java Thread Life Cycle
The following diagram shows the complete life cycle of a thread.
NEW:A new thread begins its life cycle in the new state.A NEW Thread (or a Born Thread) is a
thread that’s been created but not yet started. It remains in this state until we start it using
the start() method.
RUNNABLE:Threads in this state are either running or ready to run, but they’re waiting for
resource allocation from the system.
RUNNING:When thread is executing, it’s state is changed to Running. Thread scheduler picks
one of the thread from the runnable thread pool and change it’s state to Running. Then CPU
starts executing this thread.
BLOCKED:A thread is in the BLOCKED state when it’s currently not eligible to run. It enters
this state when it is waiting for a monitor lock and is trying to access a section of code that is
locked by some other thread.
WAITING:A thread is in WAITING state when it’s waiting for some other thread to perform a
particular action.
DEAD:This is the state of a dead thread. It’s in the TERMINATED state when it has either
finished execution or was terminated abnormally.
IMPLEMENTING THE RUNNABLE INTERFACE
Implementing the Runnable interface using keyword ’run’.The runnable interface declare
run method is required for implementing thread in your program.
The following steps are:
1. Declare the class implementing runnable interface.
2. Implement the run()method.
3. Create a thread by define an object.
4. Call the threads start()method to run the thread.
Example:
Class A implements Runnable
{
Public void run()
{
For(int i=0;i<=10;i++)
{
System.out.println(“thread x”,+i);
}
}
Class Runnabletest
{
Public static void main(String args[])
{
x runnable=new x();
Thread y=new Thread(runnable);
y.start();
System.out.println(“end”);
}
}
}
MANAGING ERRORS AND EXCEPTIONS
What are Exceptions?
Exceptions are events that disrupt normal program flow.
Types of Exceptions
1. Checked Exceptions: Must be handled at compile-time (e.g., IOException).
2. Unchecked Exceptions: Occur at runtime (e.g., ArithmeticException).
Exception Handling
Using try-catch Block
Handle exceptions to prevent program crashes.
java
Copy code
public class Main {
public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero: " + e);
}
}
}
Using finally Block
Ensures code execution regardless of exceptions.
java
Copy code
public class Main {
public static void main(String[] args) {
try {
int[] arr = new int[3];
arr[5] = 10;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Index out of bounds");
} finally {
System.out.println("Execution complete");
}
}
}
Throwing Exceptions
Use throw to explicitly raise an exception.
java
Copy code
public class Main {
static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Not eligible for voting");
} else {
System.out.println("Eligible for voting");
}
}
public static void main(String[] args) {
checkAge(16);
}
}