LearnFrenzy
Sign in Take a free test

Java Programming · Topic 10 of 28

Access Modifiers and Packages

  • 4 exercises
  • 60 questions
  • ~60 min
  • Answers explained

Coding Techniques

Access Modifiers and Packages · Study material

Expose a minimal public API

Start every member as private and widen it only when another class truly needs it. Return read-only views of internal collections.

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {
    // A class exposes a small public API and hides everything else
    static final class Playlist {
        private final List<String> songs = new ArrayList<>();   // private state
        private static final int MAX = 3;                        // private constant

        public boolean add(String song) {                        // public operations
            if (songs.size() >= MAX || songs.contains(song)) return false;
            songs.add(normalise(song));
            return true;
        }

        public List<String> songs() { return Collections.unmodifiableList(songs); }   // read-only view

        private static String normalise(String s) { return s.strip(); }               // private helper
    }

    public static void main(String[] args) {
        Playlist p = new Playlist();
        System.out.println(p.add(" Kesariya ") + " " + p.add("Naatu Naatu") + " " + p.add("Jai Ho") + " " + p.add("Extra"));
        try {
            p.songs().add("Hacked");
        } catch (UnsupportedOperationException e) {
            System.out.println("read-only: " + p.songs());
        }
    }
}

Output

true true true false
read-only: [Kesariya, Naatu Naatu, Jai Ho]

Organising packages by feature

// ✔ package by feature – related classes stay together and can use package-private access
com.learnfrenzy.orders      Order, OrderService, OrderRepository, OrderValidator (package-private)
com.learnfrenzy.payments    Payment, PaymentGateway, RazorpayGateway (package-private)
com.learnfrenzy.users       User, UserService

// ✘ package by layer – everything must be public to talk across packages
com.learnfrenzy.controllers / services / repositories / models

Resolving name conflicts

import java.util.List;                 // the one you use most gets the short name
import java.util.Date;

class Report {
    List<String> lines;                       // java.util.List
    java.awt.List widget;                     // fully qualified: the AWT component
    Date created;                             // java.util.Date
    java.sql.Date sqlDate;                    // fully qualified
}
// Single-type imports beat wildcard imports, and a class in the same file or package
// beats a wildcard import with the same simple name.

Access modifier checklist

  • Fields: private (constants may be public static final).
  • Helper methods: private.
  • Methods for subclasses to customise: protected.
  • Classes used only inside a feature package: package-private.
  • Public API: public, documented and kept small.
  • Use reverse-domain, lower-case package names.
  • In libraries, export only API packages from module-info.java.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About Java Programming

Java is one of the most used languages in the world – for enterprise software, Android apps, banking systems and backend services. This section covers core Java from syntax and data types to OOP, strings, arrays, exceptions, collections and multithreading, with clear explanations and practice questions for every topic.

Why it matters

  • Java is the main language in service-company placement tests and many product companies
  • OOP, String, collections and exception questions appear in nearly every Java interview
  • Strong core Java is the base for Spring Boot, Android and backend development
  • Java questions are common in university exams and certification tests

Who it is for

  • School students (Class 11–12 / ICSE computer applications) learning Java
  • College students (B.Tech, BCA, MCA) preparing for exams, labs and projects
  • Freshers preparing for placements, Java developer roles and technical interviews
  • Developers revising core Java before an interview

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs that train you to spot bugs quickly
  • Complete programs with solutions and real output, verified on a compiler

Asked in

  • Campus placements
  • Java developer interviews
  • Service company tests
  • University exams
  • Certification exams
  • Government IT exams

How to use this section

  1. Read the study material of a topic and run the examples yourself.
  2. Practise the four exercises – MCQs, output, errors, programs – and read every explanation.
  3. Test yourself with the timed online test, then revise the topics you got wrong.

Search LearnFrenzy

Esc

Quick links