AP Computer Science A: Class Creation and Constructor Mechanics
Class Structure and Access Modifiers
A Java class defines state via instance fields and behavior via constructors and methods in a file matching the class name.
privatefields restrict direct access from outside classes to protect encapsulation.publicconstructors and methods define the accessible interface for client programs.Instance fields must be declared outside constructors; declaring a variable inside a constructor creates a local variable that does not persist with the object.
Constructor Syntax and State Initialization
Constructors initialize instance variables, share the exact name of the class, and have no return type.
Declaring a return type (such as
void) turns a constructor into a standard method.Proper initialization requires assigning parameter values to fields using
field = parameter;; writingparameter = field;fails to update the object's state.Each object created using
newmaintains its own distinct instance fields in memory.
Default Values and Constructor Overloading
If a class provides no constructors, the compiler automatically generates a no-argument default constructor.
Default field values assigned by the compiler: primitive integers to
, floating-point numbers to, booleans tofalse, and reference types tonull.Defining any custom constructor removes the automatic implicit default constructor.
Constructor overloading allows multiple constructors in the same class, provided each has a unique parameter signature.
Reference Types, Immutability, and Defensive Copying
Assigning a mutable object reference directly from a parameter shares the underlying object, allowing external modifications to alter internal state.
Encapsulation of mutable fields requires a defensive copy, instantiating a new object with the source object's values.
Immutable objects, such as
String, do not require defensive copies and can be assigned directly.
Computed Fields and Math Utility Methods
Constructors can derive field values using calculations and static methods from the
Mathclass:Math.abs(x)computes absolute values forintanddoublearguments.Math.pow(base, exponent)andMath.sqrt(value)always return adouble.
Math.random()returns a pseudorandomdoublein the half-open interval.Scaled integer generation requires casting after scaling:
(int)(Math.random() * 900) + 100generates values in the range.(int)Math.random() * 6 + 1casts the random value tobefore multiplying, always evaluating to.
Software Reliability and Code Reuse
Reliable programs satisfy behavioral specifications across ordinary input values and edge boundary conditions.
System design requires evaluating potential harms, including the unintended exposure of private user data.
Publicly available or open-source software remains bound by legal licenses and terms of use that must be met prior to code reuse.