Java Module 5
Java Module 5
MODULE 5
Definition:
A package in Java is a namespace that organizes a set of
related classes and interfaces. It helps avoid name conflicts
and controls access with protection levels.
Types of Packages:
Benefits:
Code reusability
Better namespace management
Easy to locate classes and interfaces
Creating a Package:
// Save as MyClass.java
package mypack;
import mypack.MyClass;
Definition:
An interface in Java is a blueprint for a class. It contains
abstract methods that must be implemented by classes.
Syntax:
interface InterfaceName {
returnType methodName();
}
Example:
interface Drawable {
void draw();
}
Features:
Interfaces support multiple inheritance.
From Java 8 onward, interfaces can have default and static
methods.
1. private Access:
The member is accessible only within the class in which it is
declared.
It cannot be accessed from outside the class, not even from
subclasses or other classes in the same package.
Example:
class A {
private int x = 10;
}
Example:
class A {
int x = 10; // default access
}
3. protected Access:
The member is accessible within the same package and also in
subclasses outside the package.
It is mainly used in inheritance.
Example:
class A {
protected int x = 10;
}
4. public Access:
The member is accessible from any other class, regardless of
the package.
It's the least restrictive access level.
Example:
public class A {
public int x = 10;
}
Types:
Checked Exception: Handled at compile time (e.g.,
IOException)
Unchecked Exception: Handled at runtime (e.g.,
ArithmeticException)
Example:
Importance:
Prevents program crash
Allows graceful error handling
Syntax:
try {
// Code that might throw exception
} catch (ExceptionType name) {
// Code to handle exception
}
Example:
Use:
Detect and handle run-time errors
Avoids abnormal program termination
Types of Exceptions:
1. Checked Exceptions
o Detected during compilation
o Must be handled explicitly
1. try block:
It contains the code that may throw an exception.
2. catch block:
It is used to catch and handle the exception thrown from the try
block.
3. finally block:
This block always executes after try and catch, regardless of
whether an exception occurred or not. It is used to close
resources.
4. throw keyword:
Used to explicitly throw an exception from a method or block.
5. throws keyword:
Used in method signatures to declare that a method may throw
one or more exceptions.
Definition:
Types:
Interface inside interface
Interface inside class
Example:
interface Outer {
void display();
interface Inner {
void show();
}
}