3.1 Class Declarations, Field/Method Signatures, and Access Modifiers

Key Takeaways

  • A Java source file (.java) can have at most one public top-level class, which must match the filename case-sensitively, though it may contain multiple package-private classes.

  • Member access modifiers form a strict hierarchy (public > protected > package-private > private); protected members are accessible across package boundaries only through inheritance within the subclass context.

  • Method signatures consist solely of the method name and parameter types in order; return types, access modifiers, and throws clauses do not differentiate overloaded methods.

  • Overload resolution follows a strict four-tier precedence: exact matches, followed by primitive widening, autoboxing/unboxing, and finally varargs.

  • Varargs parameters must appear as the final parameter in a formal parameter list and at most one varargs parameter is permitted per method declaration.

Last updated: October 2026

Class Declarations, Field/Method Signatures, and Access Modifiers

Object-oriented programming in Java begins with the precise structural declaration of classes, their packages, and their accessible members. The Oracle Java SE 17 Developer certification exam tests subtle rules regarding top-level declarations, import resolution, cross-package accessibility, and method dispatch resolution.


1. Class Declarations and Class Modifiers

A top-level class declaration introduces a reference type to the Java compiler. At the class level, access and behavior are governed by a specific subset of access modifiers and non-access specifiers.

Top-Level Access Modifiers

A top-level class can only use two access levels:

  1. public: Accessible by any other class in any package across modular boundaries (assuming the package is exported if inside a Java module).
  2. Package-Private (Default): Declared without an explicit access modifier. Accessible only by classes residing in the identical package.

Warning

Declaring a top-level class as private or protected results in a compilation error: modifier private/protected not allowed here. These modifiers are only permitted on nested or inner classes.

Source File Structure Rules

  • A single .java compilation unit can declare at most one public top-level class.
  • If a public class is present, the filename must match the name of the public class exactly, including case (e.g., public class UserAccount must reside in UserAccount.java).
  • A source file may contain multiple top-level classes provided that none or only one of them is public. The non-public classes have package-private accessibility.

Non-Access Class Specifiers

  • final: Prevents the class from being extended by any subclass. Common examples in the Java standard library include java.lang.String, java.lang.Integer, and java.lang.Math.
  • abstract: Denotes an incomplete class that cannot be directly instantiated via new. An abstract class serves as a supertype for concrete subclasses.
  • strictfp: In Java 17, strictfp is effectively obsolete. Under JEP 306, Java SE 17 restored consistently strict floating-point semantics (strict conformance to IEEE 754) for all floating-point expressions across all platforms. While the strictfp keyword remains valid syntax for backward compatibility, specifying it has no operational effect.

Warning

The combination final abstract (or abstract final) is an illegal modifier collision and causes a compile-time error: illegal combination of modifiers: abstract and final. An abstract class demands extension, whereas a final class prohibits it.


2. Package Structure and Import Mechanics

Package Declarations

A package declaration groups related classes into a shared namespace. If present, the package statement must be the first non-comment, non-whitespace token in the .java file. If omitted, the compilation unit belongs to the unnamed default package.

package com.exam.model; // Must be line 1 (ignoring comments)

import java.util.List;

public class Inventory {}

Import Types and Shadowing

Java provides three distinct import styles:

  1. Single-Type Import: import java.util.List; imports a specific type.
  2. Type-Import-on-Demand (Wildcard): import java.util.*; imports all public classes and interfaces within java.util. Wildcards do not import subpackages. For example, import java.util.*; does not import java.util.concurrent.ConcurrentHashMap.
  3. Static Import: Imports static members (fields or methods) directly into scope without qualifying them with the class name.
import static java.lang.Math.PI;
import static java.lang.Math.sqrt;
import static java.util.Collections.*;

Warning

Static imports must import static members, not classes. Writing import static java.lang.Math; fails compilation with canonical name expected. To import the Math class itself, write import java.lang.Math;.

Naming Collisions and Precedence

When two packages contain a class with the same simple name, precedence determines how the name resolves:

  1. Single-type imports take precedence over wildcard imports. If import java.util.Date; and import java.sql.*; are both declared, Date unambiguously resolves to java.util.Date.
  2. Types in the same package take precedence over wildcard imports. A class named Date in the current package shadows import java.util.*;.
  3. Two conflicting wildcard imports cause ambiguity. If import java.util.*; and import java.sql.*; are present, referencing Date directly causes a compile-time error: reference to Date is ambiguous. The developer must use the fully qualified class name (FQCN), such as java.sql.Date d = new java.sql.Date(...);.

3. Member Access Modifiers

Class members (fields, methods, constructors, and nested types) can declare one of four access modifiers.

ModifierSame ClassSame PackageSubclass (Different Package)Non-Subclass (Different Package)
publicYesYesYesYes
protectedYesYesYes (via inheritance only)No
Package-Private (default)YesYesNoNo
privateYesNoNoNo

The protected Cross-Package Nuance

The protected access modifier permits access to any class in the same package, but across package boundaries, access is granted only to subclasses through inheritance.

A subclass in another package can access a protected member on an instance of itself (or its subclasses) or through super. It cannot access that protected member through a reference to the superclass.

// File: pkgA/SuperClass.java
package pkgA;
public class SuperClass {
    protected int rating = 10;
}

// File: pkgB/SubClass.java
package pkgB;
import pkgA.SuperClass;

public class SubClass extends SuperClass {
    public void inspect() {
        System.out.println(this.rating);   // COMPILES: accessed via inheritance
        System.out.println(super.rating);  // COMPILES: accessed via super
        
        SubClass sub = new SubClass();
        System.out.println(sub.rating);    // COMPILES: accessed through SubClass reference
        
        SuperClass sup = new SuperClass();
        // System.out.println(sup.rating); // COMPILE ERROR: rating has protected access in SuperClass
    }
}

4. Method Signatures and Declarations

A method signature is strictly composed of two elements: Method Signature=Method Name+Formal Parameter Types (in order)\text{Method Signature} = \text{Method Name} + \text{Formal Parameter Types (in order)}

Return types, access modifiers, optional specifiers (static, final, synchronized), and throws clauses are part of the method declaration, but not part of the signature.

Valid Method Declaration Format

[access_modifier] [specifiers] <return_type> <methodName>([parameters]) [throws_clause] { ... }
  • A method must declare a return type (or void). A constructor does not declare any return type. If a method shares the class name but declares a return type (public void User()), it is a regular method, not a constructor.
  • Specifiers (static, final, synchronized, native) can appear in any order relative to each other, but must precede the return type.

5. Method Overloading Mechanics

Method overloading occurs when two or more methods in the same class share the exact same method name but possess different parameter lists (differing in count, types, or order).

public void compute(int a, double b) {}   // Method 1
public void compute(double a, int b) {}   // Method 2: Overloaded (different parameter order)
public int compute(int a) { return a; }   // Method 3: Overloaded (different parameter count)
// public int compute(int a, double b) {} // COMPILE ERROR: Duplicate signature with Method 1

Warning

Changing only the return type, access modifier, or throws list does not constitute an overload. If the parameter types match an existing method, the compiler flags a duplicate method error.

Overload Resolution Precedence

When resolving which overloaded method to invoke, the Java compiler processes arguments through four distinct phases in strict hierarchical order:

Tier 1: Exact Match / Subtyping (widening reference types without boxing)
   ↓
Tier 2: Primitive Widening (byte -> short -> int -> long -> float -> double)
   ↓
Tier 3: Autoboxing / Unboxing (int <-> Integer)
   ↓
Tier 4: Variable-Length Arguments (Varargs: ...)
public class OverloadDemo {
    static void process(long n)    { System.out.print("long "); }
    static void process(Integer n) { System.out.print("Integer "); }
    static void process(int... n)  { System.out.print("varargs "); }

    public static void main(String[] args) {
        int x = 42;
        process(x); // Outputs: long (Primitive widening beats boxing & varargs)
    }
}

Key Rule on Widening and Boxing: Java will widen and then box? No. The compiler will widen a primitive to another primitive, or box a primitive to its wrapper. It will never widen a primitive and then box it to a different wrapper (e.g., an int cannot become a Long). However, once boxed, the wrapper can be widened to an interface or superclass (e.g., int -> Integer -> Number -> Object).


6. Variable-Length Arguments (Varargs)

Varargs (Type... name) allows a method to accept zero, one, or multiple arguments of a specified type.

Constraints on Varargs

  1. Position: A varargs parameter must be the last parameter in the formal parameter list.
  2. Count: There can be at most one varargs parameter per method.
  3. Representation: Inside the method body, the varargs parameter is treated as a standard array (Type[]).
public void log(String prefix, int... values) { // Legal
    System.out.println(prefix + ": Length = " + values.length);
}

// public void bad1(int... a, String... b) {} // COMPILE ERROR: Only one varargs permitted
// public void bad2(int... a, String prefix) {} // COMPILE ERROR: Varargs must be last

When passing zero arguments to log("Data"), values is an empty array (new int[0]), not null. If a method is overloaded with both a fixed-parameter version and a varargs version (e.g., test(int a) and test(int... a)), calling test(10) invokes the exact-match fixed version.

Test Your Knowledge

Given two classes residing in different packages:

package cert.parent;
public class Base {
    protected int value = 42;
}

package cert.child;
import cert.parent.Base;

public class Derived extends Base {
    public void test() {
        System.out.print(this.value + " ");
        Base b = new Base();
        System.out.print(b.value);
    }
}

What is the result of attempting to compile and run this code?

A

Both statements compile successfully and output 42 42.

B

Compilation fails at this.value because protected members cannot cross package boundaries under any circumstances.

C

Compilation fails at b.value because protected members cannot be accessed across packages using a superclass reference.

D

Both statements fail to compile because Derived must use super.value instead of this.value.

Test Your Knowledge

Consider the following class with overloaded methods:

public class Dispatcher {
    static void execute(long x) { System.out.print("long "); }
    static void execute(Integer x) { System.out.print("Integer "); }
    static void execute(int... x) { System.out.print("varargs "); }

    public static void main(String[] args) {
        int val = 5;
        execute(val);
    }
}

What is the result of compiling and executing this program?

A

The compiler reports an ambiguity error between execute(long) and execute(Integer).

B

The program prints Integer because autoboxing takes precedence over widening.

C

The program prints varargs because variable-length arguments provide a fallback for primitives.

D

The program prints long because primitive widening has higher resolution precedence than autoboxing or varargs.

Test Your Knowledge

Given the following declarations within a single source file:

import static java.lang.Math.PI;
import java.util.Date;
import java.sql.*;

public class InventoryReport {
    Date reportDate = new Date();
}

What is the compilation result for InventoryReport?

A

The code compiles successfully because the explicit single-type import java.util.Date shadows the wildcard import java.sql.*.

B

Compilation fails because the type Date is ambiguous between java.util.Date and java.sql.Date.

C

Compilation fails because static imports cannot precede regular package imports.

D

Compilation fails because wildcard imports cannot coexist with single-type imports from other packages.

Sections you finish are checked off in the contents.