Access Protection Matrix Across Packages & Importing Packages
1. Topic Introduction
Classes and packages collaborate to define Java's complete access-protection model. In Module 3 exams, drawing the 4×4 Access Protection Table (plus Same Class = 5th column) across packages p1 and p2, and knowing how import resolves class names and wildcard collisions, are guaranteed high-value topics.
p1 & p2)Think of Packages p1 and p2 as two gated apartment buildings. Inside Protection (p1): **private** is your locked bedroom (only Protection enters); **default** is your building's residents-only lobby (Derived and SamePackage in p1 enter, nobody in p2 enters); **protected** adds family visiting from Building p2 (Protection2 extends Protection enters!); **public** is the street open to OtherPackage too!
private = same class only; default = same package only; protected = same package + subclasses in OTHER packages; public = everywhere. java.lang.* is imported implicitly!3. Essential Exam Definitions
import Statementpackage and before class declarations (import pkg.ClassName; or import pkg.*;) bringing external packaged classes into unqualified scope.default) Accesspublic, private, protected) is written; restricts visibility strictly to classes inside the same package.4. Detailed Technical Explanation & Syntax
1. Four Categories of Visibility Across Packages (p1 vs p2)
Java defines four visibility relationships for class members outside their own class (shown in the famous p1/p2 textbook example from your slides):
- 1. Same Class (
p1.Protection): Can access ALL four (private,default,protected,public). - 2. Subclass in Same Package (
p1.Derived extends Protection): Accessesdefault,protected,public— CANNOT accessprivate. - 3. Non-subclass in Same Package (
p1.SamePackage): Accessesdefault,protected,public— CANNOT accessprivate. - 4. Subclass in Different Package (
p2.Protection2 extends p1.Protection): Accesses ONLYprotectedandpublic— CANNOT accessprivateordefault! - 5. Non-subclass in Different Package (
p2.OtherPackage): Accesses ONLYpublic! - Top-Level Class Rule: A non-nested class can ONLY be
public(visible everywhere; must match filename) ordefault(visible only within its own package).
2. import Statements, java.lang & Wildcard Name Collisions
Syntax: import pkg1[.pkg2].(ClassName | *);. Specific imports (import java.util.Vector;) are preferred for clarity, while wildcard imports (import java.util.*;) import all public top-level classes directly inside java.util (Note: import java.*; does NOT import sub-packages like java.util!).
Implicit Import: java.lang.* (String, System, Math, Object, Exception) is automatically imported into every Java source file by javac.
Name Collision Rule: If two wildcard-imported packages both contain a class with the same name (java.util.Date and java.sql.Date), javac stays silent UNTIL you actually use Date—at which point it raises a compile error! Fix it by qualifying explicitly: java.sql.Date d;.
5. Working Principle: Compile-Time Role of import (Zero Runtime Bloat)
import java.util.Vector;does NOT embedVector.classinside your.classfile—it is purely a compile-time shorthand so you can writeVectorinstead ofjava.util.Vector.- If a class (
Balance) in packageMyPackneeds to be used outsideMyPack,BalanceMUST be declaredpublicinsideBalance.java.
6. Examination-Ready Diagrams
Package Directory Structure & Access Scope
Illustrates how Java maps dot-separated hierarchical package names (com.ktu.oop) directly to nested OS file system directories and how CLASSPATH locates root packages.
- CLASSPATH Root: Directory (
./classesor.) from which JVM/javac begins package lookup. - Subdirectories (
com/ktu/oop): Each dot segment corresponds to an exact case-sensitive folder. - Compiled
.classFiles: Stored inside the leaf package directory (Student.class,Course.class).
- Source file declares
package com.ktu.oop;as its very first non-comment statement. - Compiled via
javac -d ./classes Student.java, which auto-createsclasses/com/ktu/oop/Student.class. - Executed via
java -cp ./classes com.ktu.oop.Studentfrom any working folder.
- Draw a tree structure starting from
CLASSPATH Root (e.g., project/classes)->p1/(Protection.class,Derived.class,SamePackage.class) andp2/(Protection2.class,OtherPackage.class). - Annotate the 4 visibility boundaries: Same Class, Same Package, Subclass in Different Package, Non-subclass in Different Package.
7. Complete Java Code Examples & Tracing
java.lang usage, explicit vs wildcard imports, and resolving a same-name class collision (java.util.Date vs java.sql.Date).| 1 | import java.util.Vector; // Explicit single-class import |
| 2 | import java.util.*; // Wildcard import |
| 3 | import java.sql.*; // Also contains a Date class! |
| 4 | |
| 5 | public class ImportAndCollisionDemo { |
| 6 | public static void main(String[] args) { |
| 7 | // String & Math work without import because java.lang.* is implicit |
| 8 | String msg = "Packages organize Java cleanly"; |
| 9 | System.out.println(msg + " (sqrt 16 = " + Math.sqrt(16) + ")"); |
| 10 | |
| 11 | Vector<String> pkgs = new Vector<>(); |
| 12 | pkgs.add("java.lang (implicit)"); |
| 13 | pkgs.add("java.util"); |
| 14 | System.out.println("Packages listed: " + pkgs); |
| 15 | |
| 16 | // Date d = new Date(); // COMPILE ERROR: reference to Date is ambiguous! |
| 17 | java.util.Date utilDate = new java.util.Date(0L); |
| 18 | java.sql.Date sqlDate = new java.sql.Date(0L); |
| 19 | System.out.println("Resolved via FQCN -> util: " + utilDate.getTime() |
| 20 | + ", sql: " + sqlDate); |
| 21 | } |
| 22 | } |
Packages organize Java cleanly (sqrt 16 = 4.0) Packages listed: [java.lang (implicit), java.util] Resolved via FQCN -> util: 0, sql: 1970-01-01
importpackagepublicprotectedprivate- Assuming
import java.*;recursively imports classes insidejava.utilorjava.io(wildcards only import one level!). - Forgetting to mark a class
publicwhen trying to import it from a different package. - Assuming
protectedallows access from a non-subclass in another package (it does NOT!).
Comparison Tables
| Visibility Category | private | default (no modifier) | protected | public |
|---|---|---|---|---|
Same Class (p1.Protection) | Yes | Yes | Yes | Yes |
Same Package Subclass (p1.Derived) | No | Yes | Yes | Yes |
Same Package Non-Subclass (p1.SamePackage) | No | Yes | Yes | Yes |
Different Package Subclass (p2.Protection2) | No | No | Yes | Yes |
Different Package Non-Subclass (p2.OtherPackage) | No | No | No | Yes |
Real-World Applications
- Framework authors mark internal helper classes package-private (
default) so users rely strictly on stablepublicAPIs.
Important KTU Exam Points
- Draw the 5×4 Access Protection Table accurately—it frequently appears for 6 or 9 marks alongside the
p1/p2(Protection,Derived,SamePackage,Protection2,OtherPackage) explanation! - Explain why
java.langneeds noimport, and how wildcard collision (java.util.*+java.sql.*) fails only upon ambiguous usage.
Memory Techniques & Revision
- Access Pyramid (Rows allowed per modifier):
private=1 row,default=3 rows,protected=4 rows,public=5 rows!
Common Pitfalls to Avoid
- Mixing up
defaultvsprotectedin the Different Package Subclass row (default= No,protected= Yes).
KTU-Style Questions & Exam-Ready Answers
Structured specifically for KTU Part A (3-mark) and Part B (6/9-mark) evaluation rubrics.
Introduction: Java combines classes and packages to enforce four levels of access protection (private, default, protected, public) across five visibility categories.
- 1. Same Class: All four modifiers (
private,default,protected,public) are accessible. - 2. Same Package (Subclass & Non-Subclass):
default,protected, andpublicare accessible;privateis hidden. - 3. Different Package Subclass: Only
protectedandpublicare accessible (privateanddefaultare blocked). - 4. Different Package Non-Subclass: Only
publicis accessible. - 5. Class-Level Rule: Non-nested classes may only be
publicordefault.
p1 (Protection, Derived, SamePackage) and p2 (Protection2, OtherPackage).Quick Understanding Check
1. A field int code; (no access modifier) is declared in package p1. Can a subclass in package p2 access code directly?