UNIT-III
Interface: Interfaces VS Abstract classes, defining an interface, implement interfaces,
accessing implementations through interface references, extending interface;
Packages: Defining, creating and accessing a package, understanding CLASSPATH,
importing packages.
Exception Handling: Benefits of exception handling, the classification of exceptions,
exception hierarchy, checked exceptions and unchecked exceptions, usage of try, catch,
throw, throws and finally, rethrowing exceptions, exception specification, built in exceptions,
creating own exception sub classes.
Here are detailed, structured, and student-friendly notes for the "Interfaces" topic in Java,
specifically focused on:
Interfaces vs Abstract Classes
Defining an Interface
Implementing Interfaces
Accessing Implementations via Interface References
Extending Interfaces
✅ Java Interfaces – Notes for Degree Students
📌 1. What is an Interface?
An interface in Java is a blueprint of a class. It is a reference type, similar to a class, that can
contain only abstract methods (until Java 7), and from Java 8 onwards, default, static, and
private methods.
Interfaces provide a way to achieve full abstraction and multiple inheritance in
Java.
📘 2. Interface vs Abstract Class
Feature Interface Abstract Class
Only abstract (Java 7), can have Can contain both abstract and
Methods
default/static (Java 8+) concrete methods
Fields public, static, final (constants only) Can have instance variables
Constructors Not allowed Allowed
Multiple
Yes No
Inheritance
Implementation Must be implemented by other classes Can be partially implemented
Feature Interface Abstract Class
Access Modifiers Methods are implicitly public Can use any access modifier
✅ Use an interface when you need to define a contract.
✅ Use an abstract class when you want to provide some common implementation.
🧩 3. Defining an Interface
🔹 Syntax:
interface Drawable {
void draw();
}
🔹 Key Points:
All methods are abstract and public by default.
Fields are public static final (constants).
🧱 4. Implementing an Interface
A class must use the implements keyword to define the functionality of interface methods.
🔹 Example:
interface Drawable {
void draw();
}
class Circle implements Drawable {
public void draw() {
System.out.println("Drawing a circle");
}
}
The class Circle must override all abstract methods of the interface Drawable.
5. Accessing Implementations Through Interface References
You can use the interface type to hold a reference to an object of the implementing class.
This allows for polymorphism.
🔹 Example:
Drawable d = new Circle(); // Interface reference
d.draw(); // Output: Drawing a circle
This helps in loose coupling and interchangeability of components.
🧬 6. Extending Interfaces
Interfaces can extend other interfaces using the extends keyword.
A child interface inherits the methods of the parent interface.
🔹 Example:
interface Printable {
void print();
}
interface Showable extends Printable {
void show();
}
class A implements Showable {
public void print() {
System.out.println("Printing...");
}
public void show() {
System.out.println("Showing...");
}
}
Java Packages – Notes for Degree Students
📘 1. What is a Package?
A package in Java is a namespace that organizes a set of related classes and interfaces.
Think of a package like a folder in your computer, used to group similar types of
files.
Packages help to avoid name conflicts, make code easier to manage, and improve
reusability.
2. Types of Packages
1. Built-in Packages
Provided by Java (e.g., java.lang, java.util, java.io, etc.)
2. User-defined Packages
Created by programmers to group related classes.
3. Defining a Package
Use the package keyword at the top of the Java file.
🔹 Syntax:
package mypackage;
public class MyClass {
public void display() {
System.out.println("Hello from MyClass in mypackage");
}
}
Save the file as MyClass.java inside a folder named mypackage.
⚙️4. Creating and Accessing a Package
✅ Step 1: Create a Package
Save your Java file inside a folder with the same name as the package.
✅ Step 2: Compile the Package
Use the -d switch to create the directory structure.
javac -d . MyClass.java
It will create a folder mypackage with MyClass.class inside.
✅ Step 3: Access the Package
Create another Java file in a different location and import the package:
import mypackage.MyClass;
class Test {
public static void main(String[] args) {–
MyClass obj = new MyClass();
obj.display();
}
}
5. Understanding CLASSPATH
CLASSPATH is an environment variable that tells the Java compiler and JVM where
to find class files.
If your class files are in a custom folder or on another drive, you need to set the
CLASSPATH.
🔹 Example:
Command-line (Windows):
set CLASSPATH=.;C:\JavaPrograms
. means current directory.
C:\JavaPrograms is where your packages or class files are stored.
🛠 6. Importing Packages
🔹 Import a Specific Class
import java.util.Scanner;
🔹 Import All Classes in a Package
import java.util.*;
🔹 No Import Needed for java.lang
Automatically imported.
String s = "Hello"; // java.lang.String
7. Commonly Used Java Packages
Package Name Purpose
java.lang Basic classes (String, Math, etc.)
Package Name Purpose
java.util Collections, Date, Scanner, etc.
java.io File handling
java.net Networking
java.sql Database connectivity (JDBC)
Exception Handling in Java :
1. What is an Exception?
An exception is an unexpected event that occurs during the execution of a program and
disrupts the normal flow of instructions.
Java handles such errors using exception handling mechanisms.
🌟 2. Benefits of Exception Handling
1. Separates normal code and error-handling code.
2. Improves program readability and maintainability.
3. Avoids abrupt program termination.
4. Provides meaningful error messages to users.
🧱 3. Classification of Exceptions
🔹 3.1 Checked Exceptions (Compile-time)
Must be handled at compile time.
Examples: IOException, SQLException, FileNotFoundException
🔹 3.2 Unchecked Exceptions (Runtime)
Occur during program execution.
Examples: ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException
4. Exception Hierarchy
Object
└── Throwable
├── Error (irrecoverable)
└── Exception
├── Checked Exceptions
└── RuntimeException (Unchecked Exceptions)
🔑 5. Exception Handling Keywords
Keyword Description
try Defines block of code to monitor for exceptions
catch Catches and handles exceptions
throw Used to throw an exception manually
throws Declares exceptions that might be thrown
finally Block that always executes
6. Syntax and Examples
✅ try-catch block
try {
int a = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}
finally block
try {
System.out.println("Try block");
} finally {
System.out.println("Finally block always executes");
}
throw keyword
throw new ArithmeticException("Manually thrown exception");
throws keyword
void myMethod() throws IOException {
throw new IOException("File error");
}
🔁 7. Rethrowing Exceptions
You can catch an exception and throw it again.
try {
throw new IOException("Error occurred");
} catch (IOException e) {
System.out.println("Caught: " + e);
throw e; // rethrowing
}
⚠️8. Exception Specification
(Deprecated in Java 8)
Earlier Java versions allowed method declarations to list all thrown exceptions using throws.
void readFile() throws IOException, SQLException {
// method code
}
📚 9. Built-in Exceptions
Exception Description
ArithmeticException Division by zero
NullPointerException Accessing object with null reference
ArrayIndexOutOfBoundsException Invalid index access in arrays
NumberFormatException Invalid conversion of string to number
FileNotFoundException File not found
10. Creating Custom Exception (User-defined)
You can create your own exception class by extending the Exception class.
🔹 Example:
class InvalidAgeException extends Exception {
InvalidAgeException(String msg) {
super(msg);
}}
public class Test {
static void validate(int age) throws InvalidAgeException {
if (age < 18)
throw new InvalidAgeException("Not eligible to vote");
}
public static void main(String[] args) {
try {
validate(15);
} catch (InvalidAgeException e) {
System.out.println("Exception caught: " + e.getMessage());
}
}
}