← Back to Home

User-Defined Packages

User-defined packages are packages created by developers to organize application classes and interfaces in a logical, modular, and maintainable structure. They are essential for real-world Java projects, team collaboration, and large codebases. This is a common interview topic, often asked after built-in packages.

What Is a User-Defined Package?

  • A package created by the developer
  • Groups related classes and interfaces
  • Provides namespace and access control
  • Improves code organization and reusability
package com.mycompany.project.util;
          

Why User-Defined Packages Are Needed

  • Organize large applications
  • Avoid class name conflicts
  • Improve readability
  • Support layered architecture
  • Enforce access control using modifiers

Creating a User-Defined Package

1️⃣ Using package Keyword (Source Code Level)

package com.example.util;
public class MathUtil {
    public static int add(int a, int b) {
        return a + b;
    }
}
          

Rules:

  • package statement must be first line
  • Only one package per class

2️⃣ Compile and Create Directory Structure

javac -d . MathUtil.java
          

✔ Creates:

com/
 └── example/
     └── util/
         └── MathUtil.class
          

Accessing User-Defined Package Classes

1. Using Fully Qualified Name

com.example.util.MathUtil.add(2, 3);
          

2. Using import Statement

import com.example.util.MathUtil;
MathUtil.add(2, 3);
          

3. Using Wildcard Import

import com.example.util.*;
          

⚠️ Imports only classes in that package, not sub-packages

Package Naming Conventions (Very Important)

  • All lowercase
  • Reverse domain naming
  • Descriptive hierarchy
com.company.project.layer
          

Examples:

  • com.amazon.payment.service
  • org.apache.commons.lang

User-Defined Packages and Access Modifiers

Modifier Same Class Same Package Subclass (diff pkg) Everywhere
private
default
protected
public

✔ Packages define visibility boundaries

Sub-Packages (Clarification)

com.bank
 └── account
 └── loan
          
  • ✔ Sub-packages are independent
  • ❌ No automatic access to parent package members

Creating Multiple Classes in Same Package

package com.app.service;
public class UserService { }
class HelperService { }
          
  • ✔ Only one public class per file
  • ✔ Others have default access

Packaging into JAR (Real-World Usage)

jar cf app-utils.jar com/example/util/*.class
          
  • ✔ Distribute and reuse packages
  • ✔ Used in libraries and frameworks

Common Beginner Mistakes

  • Forgetting package statement
  • Incorrect folder structure
  • Using uppercase letters in package names
  • Assuming sub-packages inherit access
  • Overusing wildcard imports

Interview-Ready Answers

Short Answer

A user-defined package is a package created by developers to organize application classes.

Detailed Answer

In Java, user-defined packages are created using the package keyword to group related classes and interfaces. They help organize large applications, avoid naming conflicts, and enforce access control. Developers commonly follow reverse domain naming conventions when creating packages.

Key Takeaway

User-defined packages bring structure and scalability to Java applications. They are essential for clean architecture, modular development, and enterprise-level Java projects.

User-Defined Package Examples

1. Creating a Simple User-Defined Package

package com.app.util;

public class MathUtil {
    public static int add(int a, int b) {
        return a + b;
    }
}
          

Explanation

  • Package statement must be the first line
  • Class is public → accessible outside the package

2. Using User-Defined Package Class

import com.app.util.MathUtil;

class Demo {
    public static void main(String[] args) {
        System.out.println(MathUtil.add(2, 3));
    }
}
          

Output

5

3. Package with Multiple Classes

package com.app.model;

public class User {
    public String name = "Admin";
}

package com.app.model;

public class Role {
    public String role = "ADMIN";
}
          

4. Accessing Multiple Classes from Same Package

import com.app.model.User;
import com.app.model.Role;

class Demo {
    public static void main(String[] args) {
        User u = new User();
        Role r = new Role();
        System.out.println(u.name + " - " + r.role);
    }
}
          

Output

Admin - ADMIN

5. Using import package.*

import com.app.model.*;

class Demo {
    public static void main(String[] args) {
        User u = new User();
        System.out.println(u.name);
    }
}
          

Explanation

  • Imports all public classes
  • Not recommended in large codebases

6. Default (No Modifier) Access in User Package

package com.app.internal;

class Helper {
    void help() {
        System.out.println("Internal help");
    }
}

package com.app.client;

// Helper h = new Helper(); // ❌ not accessible
          

Explanation

  • Default access → same package only

7. protected Access Across Packages (Inheritance)

package p1;

public class Base {
    protected void show() {
        System.out.println("Protected method");
    }
}

package p2;

import p1.Base;

class Child extends Base {
    public static void main(String[] args) {
        new Child().show();
    }
}
          

Output

Protected method

8. Same Class Name in Different Packages

package p1;
public class Test {
    public void show() {
        System.out.println("p1 Test");
    }
}

package p2;
public class Test {
    public void show() {
        System.out.println("p2 Test");
    }
}
          

9. Resolving Name Conflict Using Fully Qualified Name

class Demo {
    public static void main(String[] args) {
        p1.Test t1 = new p1.Test();
        p2.Test t2 = new p2.Test();
        t1.show();
        t2.show();
    }
}
          

Output

p1 Test
p2 Test
          

10. Static Import from User-Defined Package

package com.app.util;

public class Constants {
    public static final int TIMEOUT = 30;
}

import static com.app.util.Constants.TIMEOUT;

class Demo {
    public static void main(String[] args) {
        System.out.println(TIMEOUT);
    }
}
          

Output

30

11. Nested (Sub) Packages

package com.app.service.auth;

public class AuthService {
    public void login() {
        System.out.println("Login success");
    }
}

import com.app.service.auth.AuthService;

class Demo {
    public static void main(String[] args) {
        new AuthService().login();
    }
}
          

Output

Login success

12. Directory Structure Matching Package

src/
 └── com/
     └── app/
         └── service/
             └── auth/
                 └── AuthService.java
          

Explanation

  • Folder structure must match package name

13. Compiling User-Defined Package

javac -d . MathUtil.java

Explanation

  • -d . creates package directories automatically

14. Running Class from User Package

java com.app.util.MathUtil

Explanation

  • Fully qualified class name required

15. Creating JAR from User Package

jar cf app-util.jar com/app/util/*.class

16. Using User Package from JAR

javac -cp app-util.jar Demo.java
java  -cp .;app-util.jar Demo
          

17. User Package + Interface

package com.app.api;

public interface Service {
    void execute();
}

package com.app.impl;

import com.app.api.Service;

public class ServiceImpl implements Service {
    public void execute() {
        System.out.println("Executed");
    }
}
          

18. Real-World Automation Framework Package Structure

com.framework
 ├── base
 ├── pages
 ├── tests
 ├── utils
 └── config
          

Explanation

  • Improves modularity & maintainability

19. Access Rule Summary Example

package p1;

public class A {
    public int x = 10;
    protected int y = 20;
    int z = 30;
    private int w = 40;
}

package p2;

import p1.A;

class Demo extends A {
    void test() {
        System.out.println(x); // ✔
        System.out.println(y); // ✔
        // System.out.println(z); // ❌
        // System.out.println(w); // ❌
    }
}
          

20. Interview Summary – User-Defined Packages

package com.demo;

public class Test {
    public static void main(String[] args) {
        System.out.println("User-defined package");
    }
}
          

Key Points

  • Organizes related classes
  • Prevents name conflicts
  • Controls access
  • Essential for real projects

Output

User-defined package