Unlock Your Python Backend Career: Build 30 Projects in 30 Days. Join now for just $54

Methods in Java

Java Access Modifiers & Packages

Java Packages are collections of classes, interfaces, and sub-packages. In Java, with the help of packages, we can group related classes.

A package is like a folder inside the file directory. We use packages to avoid name conflicts and write more maintainable code.

Packages allow developers to create software that is easier to maintain, scale, and extend by grouping relevant code.

In addition to facilitating code reuse across projects and teams, packages also help maintain consistent naming conventions.

Java Packages.pngIn Java, a package is a directory that contains Java source code files. The package name corresponds to the directory name, and each Java file contains a class with a matching filename. For example, if your class is in a folder called com/example, and the class name is ClassName, then its full name will be com.example.ClassName.

To prevent naming conflicts, Java developers typically name their packages using their company's domain name in reverse order. For instance, if your company's website is example.com, your package name would begin with com. example. Similarly, if your domain is masteringbackend.com, the package name would begin with com. masterbackend. We can also create sub-packages—directories nested within other packages. For example, com.masterbackend.util is a sub-package of com .masteringbackend. This hierarchical organization helps maintain a clean and navigable codebase.

Syntax

1. Declaration package

Java package statement comes at the top of the file, with the help of the package keyword, we write the package. Here, util is the sub-package of the com. example.

package com.example.util;

2. Import statement

If we want to use a class, interface, and enum from another package, then we import the package by using the import keyword.

import com.example.model.User;

Here we are importing the class User from the model package, which is a sub-package of com. example. If we want to import all the classes that are present inside the model package, then we use * wildcard.

import com.example.model.*;

Example

package com.example.model;

public class User {
    private String name;

    // Constructor
    public User(String name) {
        this.name = name;
    }

    // Getter method
    public String getName() {
        return name;
    }

    // Setter method (optional)
    public void setName(String name) {
        this.name = name;
    }
}

Here, in this example model is a package under the com example, and the user is a class under the package model. Now, if we want to use this class in another package class, then we need to import this class.

package com.example.util;

import com.example.model.User;

public class Helper {
    public void printUser(User user) {
        System.out.println(user.getName());
    }
}

By using import com.example.model.User. We import the User class from the model package.

File Structure

The file structure is created like this:

src/
├── com/
│   └── example/
│       ├── model/
│       │   └── User.java
│       └── util/
│           └── Helper.java

Types of Java Packages

There are two types of packages in Java

1. User-defined packages

2. Built-In packages

User-defined packages

The packages created by the developers are known as user-defined packages.

To create our package, we need to understand that Java uses a file system directory to store it, just like folders on your computer.

Example

└── root
  └── mypack
    └── MasterBackend.java

For creating packages, we use the package keyword. Here, root is a package and mypack is a subpackage under the root, and the MasterBackend is a class inside the mypack.

package mypack;

class MasterBackend{
	pblic static void main(String[] args) {
    System.out.println("This is my package!");
  }
}

Built-in Packages

Built-in packages are provided by the Java API, which is a library of prewritten classes included in the Java Development Environment.

The library contains components for managing input, database programming, and much more.

import root.mypack.MasterBackend;   // Import a single class
import root.mypack.*;   // Import the whole package

The library is divided into packages and classes. Meaning you can either import a single class (along with its methods and attributes) or an entire package containing all classes within it.

For built-in packages, we import the package and use it inside the application or class. If we want to import a single class from the built-in package, then we write the import root. mypack.MasteringBackend, if we want to import the complete mypack, then we use * to import all the classes and interfaces inside the mypack.

Example

The Scanner class is used to read input from the user, like numbers or text typed from the keyboard. It is part of java.util package. Which is a built-in package provided by Java.

Here we are importing the Scanner class from the util package.

import java.util.Scanner;

public class InputExample {
    public static void main(String[] args) {

        // Creating a Scanner object to take input from the keyboard
        Scanner scanner = new Scanner(System.in);

        // Asking the user to enter their name
        System.out.print("Enter your name: ");
        String name = scanner.nextLine(); // Reads a line of text

        // Asking the user to enter their age
        System.out.print("Enter your age: ");
        int age = scanner.nextInt(); // Reads an integer

        // Printing the input back
        System.out.println("Hello, " + name + "! You are " + age + " years old.");

        // Closing the Scanner to free up resources
        scanner.close();
    }
}

Built-in packages in

  • java.lang – Core classes like String, Math, System; imported by default.

  • java.util – Utility classes such as ArrayList, HashMap, Scanner, and Date.

  • java.io – For input and output operations like reading/writing files.

  • java.net – Supports networking features like sockets, URLs, and HTTP connections.

  • java.sql – Provides classes for database access and SQL operations.

  • java.time – Modern date and time API introduced in Java 8.

  • java.math – Classes for high-precision math, like BigInteger and BigDecimal.

  • java.nio – Non-blocking I/O operations and advanced file handling.

  • java.security – Tools for secure coding, encryption, and authentication.

  • javax.swing – Used for building GUI applications in Java.

  • javax.servlet – For creating server-side web components like servlets.

For a complete list, visit Oracle’s website.

Top-Level classes

The only applicable modifiers for Top Level classes are:

1. Public

2. Default

3. Final

4. Abstract

5. Strictfp

If we are using any other modifier, we will get a compile-time error.

There are two types of modifiers.

1. Access Modifiers

2. Non-access Modifiers

Access Modifiers

Whenever we are creating a class, it is compulsory that we have to provide some information about our class to the JVM. Like, the class can be accessible from anywhere or not.

If accessible, then what is the access level of the class? All these things we set with the help of access modifiers.

Java provides several access modifiers to set the level of access for a class and its members (fields, methods, constructors).

This is also known as the visibility of the class, field, and methods. When no access modifier is mentioned for a class member, the default accessibility is package or default.

Access modifiers in Java specify the accessibility or scope of a field, method, constructor, or class. We can change the access level of fields, constructors, methods, and classes by applying the access modifier to them.

Java Access Modifiers.pngThere are four types of Java access modifiers

1. Private

2. Default

3. Protected

4. Public

Syntax

// Class Access Modifiers
public class ClassName { }
class DefaultClassName { } // default (no modifier)

// Interface Access Modifiers
public interface InterfaceName { }

// Constructor Access Modifiers
public ClassName() { }
protected ClassName() { }
ClassName() { } // default
private ClassName() { }

// Variable Access Modifiers
public int publicVar;
protected int protectedVar;
int defaultVar; // default (package-private)
private int privateVar;

// Method Access Modifiers
public void publicMethod() { }
protected void protectedMethod() { }
void defaultMethod() { } // default
private void privateMethod() { }

// Enum Access Modifiers
public enum EnumName { VALUE1, VALUE2 }
enum DefaultEnumName { VALUE1, VALUE2 } // default

Public Modifier

Accessible from anywhere: within the class, outside the class, within the package, and outside the package. When we create the class as public, then we can access the class from anywhere. When we mark the class, constructor, interface, or data members of a class as public, then we can access them everywhere.

Syntax

public class ClassName { }

public enum EnumName { VALUE1, VALUE2 }

public void publicMethod() { }

public ClassName() { }

public interface InterfaceName { }

image (13).pngHere in the above image, when class A is public, we can access it within the package as well as outside of the package.

Example

// File: Main.java
public class Main {
    public static void main(String[] args) {
        Car car = new Car();  // public class, accessible anywhere
        car.drive();          // public method, accessible anywhere
    }
}

// File: Car.java
public class Car {
    public void drive() {
        System.out.println("Car is driving");
    }
}

In this example, we declare the class and the method drive() public, so they can be accessed from any other class or package.

Private Modifier

Accessible only within the class. It cannot be inherited or accessed outside. When the class is private, we can’t inherit from another class, If we make the variable private, we can access it from outside the class. If we mark the constructor as private, we can’t create the object of the class outside of the class scope.

Syntax

private class ClassName { }

private enum EnumName { VALUE1, VALUE2 }

private void publicMethod() { }

private ClassName() { }

private interface InterfaceName { }

image (14).pngHere in the above image, when class A is private, we can’t access it within the package as well as outside of the package.

Example

// File: Main.java
public class Main {
    public static void main(String[] args) {
        Truck truck = new Truck();
        truck.show();  // Only public method can be accessed
    }
}

// File: Truck.java
public class Truck {
    private void move() {
        System.out.println("Truck is moving");
    }

    public void show() {
        move();  // private method accessed within same class
    }
}

Here in this example, inside the truck class, we create a method as move that is accessible only within the class, not outside of the class, because of private and accessible only inside the same class where it's declared.

Whenever you're ready

There are 4 ways we can help you become a great backend engineer:

The MB Platform

Join 1000+ backend engineers learning backend engineering. Build real-world backend projects, learn from expert-vetted courses and roadmaps, track your learnings and set schedules, and solve backend engineering tasks, exercises, and challenges.

The MB Academy

The “MB Academy” is a 6-month intensive Advanced Backend Engineering BootCamp to produce great backend engineers.

Join Backend Weekly

If you like post like this, you will absolutely enjoy our exclusive weekly newsletter, Sharing exclusive backend engineering resources to help you become a great Backend Engineer.

Get Backend Jobs

Find over 2,000+ Tailored International Remote Backend Jobs or Reach 50,000+ backend engineers on the #1 Backend Engineering Job Board