Java Module: Interface and Package
1. Interface in Java
An interface is a blueprint for a class. It defines what methods a class must have, but not how they
work.
It is a contract — if a class implements an interface, it must define all its methods.
Syntax:
interface InterfaceName {
void method1();
void method2();
Example:
interface Animal {
void eat();
void sleep();
class Dog implements Animal {
public void eat() {
[Link]("Dog eats bones");
public void sleep() {
[Link]("Dog sleeps in kennel");
class Main {
public static void main(String[] args) {
Dog d = new Dog();
[Link]();
[Link]();
}
}Output: Dog eats bones Dog sleeps in kennel
Key Points:
- All interface methods are abstract.
- All variables are public static final.
- A class can implement multiple interfaces.- Interfaces can extend other interfaces.
Example of Multiple Interfaces:
interface A {
void showA();
}
interface B {
void showB();
}
class C implements A, B {
public void showA() {
[Link]("This is from A");
}
public void showB() {
[Link]("This is from B");
}
}
2. Package in Java
A package groups related classes and interfaces, like folders in a computer.
It helps avoid name conflicts and organize code.
Types of Packages:
1. Built-in packages (e.g., [Link], [Link])
2. User-defined packages
Example of User-defined Package:
// Save as [Link] inside "mypack" folder package mypack; public class Animal { public void
display() { [Link]("This is the Animal class inside mypack package."); } } Use in another
file:
import [Link] ;
class TestPackage {
public static void main(String[] args) {
Animal obj = new Animal();
[Link]();
}
}
Commands to Run:
javac mypack/[Link]
javac -cp . [Link]
java -cp . TestPackage
Output:
This is the Animal class inside mypack package.
Comparison Table
Feature Interface Package
Purpose Define methods (rules) Organize classes
Keyword interface package
Implementation implements import
Example interface Animal {} package mypack;
Analogy Contract Folder