0% found this document useful (0 votes)
5 views9 pages

Understanding Java Code Modularity

The document provides an overview of code modularity, emphasizing the importance of packages and interfaces in Java for organizing code, enhancing reusability, and supporting abstraction. It details the structure and types of packages, access control, and the concept of interfaces, including their implementation and relationship with other OOP concepts. Additionally, it discusses practical implementation topics to reinforce understanding of these concepts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views9 pages

Understanding Java Code Modularity

The document provides an overview of code modularity, emphasizing the importance of packages and interfaces in Java for organizing code, enhancing reusability, and supporting abstraction. It details the structure and types of packages, access control, and the concept of interfaces, including their implementation and relationship with other OOP concepts. Additionally, it discusses practical implementation topics to reinforce understanding of these concepts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Overview of Code Modularity

Definition:
Modular programming means dividing a program into independent, smaller parts
(modules), each responsible for a specific functionality.

Each module can be developed, tested, and reused independently.

Advantages:

1. Increases code reusability.


2. Simplifies debugging and testing.
3. Improves teamwork — multiple developers can work on different modules.
4. Enhances maintainability and scalability.

Real-world Analogy:
Just like how your computer stores files in folders based on type (e.g., Documents, Music,
Pictures),
Java organizes classes into packages based on functionality.

🔹 2. Importance of Packages & Interfaces

Feature Packages Interfaces


Purpose Organize related classes and control Define rules or behavior to be followed by
visibility classes

Support Modularity Abstraction


s
Benefit Easier project structure Standardized code behavior
Used in Large enterprise applications APIs, frameworks, design patterns

Advantages:

 Encourages code reuse.


 Enhances security (via access modifiers).
 Promotes clean design.
 Enables interoperability between modules.

🔹 3. Connection with Other OOP Concepts

OOP Concept Connection


Encapsulation Packages help group related data and behavior.
Abstraction Interfaces define abstract behavior (no implementation).
Inheritance Interfaces support multiple inheritance.
Polymorphism Interface references enable dynamic method binding.

💡 In short:
Packages = logical grouping (structure)
Interfaces = behavioral contract (rules)

PACKAGES IN JAVA

1. Concept & Definition

A package is a group of related classes, interfaces, and sub-packages that are bundled
together to provide modular programming.

Purpose:

 Avoids class name conflicts.


 Organizes files logically.
 Controls access using modifiers.

Analogy:
Just as folders in your PC contain files,
packages in Java contain related classes and interfaces.

2. Types of Packages

Type Description Example

Built-in Packages Provided by Java’s standard [Link], [Link], [Link],


library. [Link], [Link]

User-defined Created by the programmer. package [Link];


Packages

Built-in Example:

import [Link];
class Example {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter name: " + [Link]());
}
}

3. Creating User-defined Packages

Syntax:

package mypackage;

public class Message {


public void show() {
[Link]("Hello from mypackage!");
}
}

Steps to Compile and Run:

1. Save as [Link]
2. Compile → javac -d . [Link] (creates a folder named mypackage)
3. Create another file to use it:

import [Link];
class Test {
public static void main(String[] args) {
Message m = new Message();
[Link]();
}
}

4. Run → java Test

4. Accessing and Using Packages

There are three ways to access a package class:

(a) Import a specific class

import [Link];

(b) Import all classes

import mypackage.*;

(c) Use fully qualified name

[Link] m = new [Link]();


5. Sub-Packages

 A sub-package is a package inside another package.


 It represents a hierarchical structure.

Example:

package [Link];

Folder Structure:

com → upnex → education → training

💡 To access, use:

import [Link].*;

6. Access Modifiers & Access Control

Java provides four access levels to control visibility.

Modifier Same Class Same Package Subclass (Diff Package) Other Package
public ✅ ✅ ✅ ✅
protected ✅ ✅ ✅ ❌

default ✅ ✅ ❌ ❌
private ✅ ❌ ❌ ❌

Example:

package school;
public class Student {
public void showPublic() {}
protected void showProtected() {}
void showDefault() {}
private void showPrivate() {}
}

From another package, only public methods are accessible.

7. Static Import

Allows direct use of static members (no class name prefix).

Example:
import static [Link].*;

class Demo {
public static void main(String[] args) {
[Link](sqrt(25)); // no need to write [Link]()
[Link](pow(2, 3)); // directly accessible
}
}

8. Advantages of Packages

1. Avoids class name conflicts.


2. Makes code easy to maintain.
3. Controls access (security).
4. Supports reusability.
5. Provides better project organization.

9. Commonly Used Java Packages

Package Common Classes


[Link] Math, String, System, Thread
[Link] ArrayList, Scanner, HashMap, Collections
[Link] File, BufferedReader, FileReader
[Link] Frame, Button, Label
[Link] Socket, URL, InetAddress

10. Advanced Topic (Optional)

 Creating JAR files:


 jar cf [Link] mypackage/
 Using CLASSPATH variable:
To add external packages.
 Java 9 Modular System ([Link]):
 module [Link] {
 exports [Link];
 }

INTERFACES IN JAVA

1. Concept & Definition

An interface in Java is a collection of abstract methods and constants that define a set of
rules or behavior that implementing classes must follow.
Purpose:

 Achieve 100% abstraction (before Java 8).


 Support multiple inheritance.
 Define common behavior across unrelated classes.

Analogy:
An interface is like a contract — a class that signs it must fulfill all its conditions.

2. Syntax
interface InterfaceName {
void methodName(); // abstract method
}

3. Implementing an Interface
interface Vehicle {
void start();
}

class Car implements Vehicle {


public void start() {
[Link]("Car starts with key ignition");
}
}

💡 Rules:

 All interface methods are public and abstract by default.


 Implementing class must declare them public.
 You cannot create objects of an interface.

4. Multiple Interface Implementation


interface A { void methodA(); }
interface B { void methodB(); }

class C implements A, B {
public void methodA() { [Link]("A implemented"); }
public void methodB() { [Link]("B implemented"); }
}

✅ Supports multiple inheritance


❌ Cannot have duplicate method signatures with conflicting return types.
5. Interface Inheritance
interface A { void methodA(); }
interface B extends A { void methodB(); }

💡 Interfaces can extend other interfaces, but classes implement them.

6. Variables in Interface

 All variables are public static final by default.

interface MathConstants {
double PI = 3.14159;
}

Usage:

[Link]([Link]);

7. Default and Static Methods (Java 8)


interface Shape {
default void info() {
[Link]("This is a shape");
}
static void display() {
[Link]("Static method in interface");
}
}

class Circle implements Shape {}

Output:

This is a shape

8. Functional Interfaces

 Interface with only one abstract method.


 Used for lambda expressions.

@FunctionalInterface
interface Greeting {
void sayHello(String name);
}

Example usage:

Greeting g = (name) -> [Link]("Hello " + name);


[Link]("Bhawani");

9. Marker Interfaces

 Interfaces with no methods or variables.


 Used to mark classes for special behavior.
Examples:
 Serializable
 Cloneable
 Remote

10. Nested Interfaces


class Outer {
interface Inner {
void show();
}
}

class Test implements [Link] {


public void show() {
[Link]("Nested interface implemented");
}
}

11. Interface and Polymorphism


interface Animal { void sound(); }
class Dog implements Animal { public void sound()
{ [Link]("Bark"); } }
class Cat implements Animal { public void sound()
{ [Link]("Meow"); } }

class Main {
public static void main(String[] args) {
Animal a = new Dog(); // interface reference
[Link]();
}
}

Output:
Bark
12. Interface vs Abstract Class

Feature Interface Abstract Class


Keyword interface abstract

Methods All abstract (till Java 7) Abstract + Concrete


Variables public static final Can be any
Constructor Not allowed Allowed
Inheritance Multiple allowed Single
Default/Static Methods Yes (Java 8+) Yes
Purpose Total abstraction Partial abstraction

13. Interface in Real-World APIs

Interface Package Use


Runnable [Link] Used in multithreading
Comparable [Link] Used for sorting objects
AutoCloseable [Link] Used in try-with-resources
List, Map, Set [Link] Collection framework

🧩 D. PRACTICAL IMPLEMENTATION TOPICS


1. Create a package college and a class Student with details. Import and access it from
another file.
2. Build package hierarchy: [Link].
3. Implement two interfaces in one class.
4. Demonstrate default and static interface methods.
5. Write a program to show marker interface (Serializable).

You might also like