Object-Oriented Programming in Java: Classes, Objects, Scope, and Methods
Foundations of Java Classes and Reference Types
Introduction of Reference Types:
- Declaring a class in Java introduces a new reference type (referenčný typ) into the program.
- Unlike primitive types (such as
int,double,boolean), which store raw values directly in memory, a reference type defines a template for objects whose variables store memory addresses (references) pointing to those objects on the heap.
Syntax of Class Declarations:
- The valid syntax for declaring a class requires access and non-access modifiers to precede the
classkeyword, followed by the class identifier and the class body enclosed in curly braces:java [modifiers] class ClassName { // fields and methods } - Placing the
classkeyword before the modifiers (e.g.,class modifikátory MenoTriedy) is invalid syntax. - Class declarations do not use parameter parentheses
()in their header (e.g.,modifikátory class MenoTriedy()is invalid syntax).
- The valid syntax for declaring a class requires access and non-access modifiers to precede the
Minimal Structural Requirements of a Class:
- A class definition does not strictly require methods to be syntactically valid.
- A class may consist exclusively of private attributes (fields):
java public class Point { private int x; private int y; }
The code above represents the valid definition of a new class named
Pointencapsulating two attributes, even without constructors, getters, setters, or custom methods.
Objects and Instantiation
Definition of an Object:
- In Java, an object is an instance of a class (inštancia triedy).
- It is not a predefined function, a primitive variable, or a data prototype.
- An object embodies both state (stored in fields/attributes) and behavior (defined by methods).
The
newKeyword and Memory Allocation:- The
newkeyword is the dedicated operator used to dynamically allocate memory on the heap and instantiate an object in Java. - Keywords such as
instance,object, orcreatedo not exist for object creation in Java.
- The
Instantiation Syntax:
- Instantiating an object requires declaring a reference variable of the class type and assigning it the newly created instance using the constructor:
java ClassName objectName = new ClassName();
- Instantiating an object requires declaring a reference variable of the class type and assigning it the newly created instance using the constructor:
For a class defined as
public class Point { private int x; private int y; }, the correct instantiation is:java Point point = new Point(); Attempting to assign an object to a primitive type (such as
int point = new Point();orint point = new int(Point);) results in a compilation error due to type incompatibility.Java is strictly case-sensitive; calling
new point()instead ofnew Point()causes a compilation error because the identifierpointdoes not match the class namePoint.
Variable Declaration, Initialization, and Scoping
Simultaneous Declaration and Initialization:
- A single statement can declare multiple variables of the same data type and simultaneously initialize them with starting values:
java private int x = 0, y = 0; - This statement achieves two operations for both
xandy: - Declaration: Specifies the access level (
private) and data type (int). - Initialization: Assigns an initial value (
0) to each variable.
- A single statement can declare multiple variables of the same data type and simultaneously initialize them with starting values:
Variable Shadowing and Precedence:
- In a method, an instance variable is never superior to a local variable; it does not shadow the local variable.
- Instead, a local variable (or method parameter) with the same identifier as an instance variable shadows (prekrýva) the instance variable within that method's scope.
- When an identifier is referenced inside a method, the Java compiler resolves it to the most local scope available.
The
thisKeyword:- The
thiskeyword is a reference to the current object instance. - Its primary role in variable management is to disambiguate and distinguish between an instance variable and a local variable or parameter that shares the same name:
java this.x = x;
- The
In this expression,
this.xexplicitly targets the instance variable of the current object, whereasxrefers to the local method parameter.The
thiskeyword does not exist to define exceptions or handle conditional logic.
Access Modifiers and Encapsulation
The
privateAccess Modifier:- To restrict access to an attribute or method exclusively to the enclosing class, the
privatemodifier must be used. - Any attempt to access a
privatemember from outside the defining class produces a compile-time access violation error. - Other access levels provide broader visibility:
public: Accessible from any other class.protected: Accessible within the same package and by subclasses in other packages.- Default (package-private, no modifier): Accessible only within classes of the same package.
- To restrict access to an attribute or method exclusively to the enclosing class, the
Encapsulation Constraints on Direct Field Access:
- Given the class declaration:
java public class Point { private int x; private int y; }
- Given the class declaration:
If an instance
pointis created in an external context:java Point point = new Point(); Direct field access expressions such as
point.xorpoint.y(e.g.,System.out.println(point.x + " " + point.y);) fail to compile becausexandyare markedprivate.Attempting to call non-existent accessor methods (e.g.,
point.getX(),point.getY()) also causes a compilation error if those methods have not been explicitly defined in the class body.Therefore, attributes declared
privatewithout public getters cannot be accessed from outside the class.
Method Declaration and Return Types
Absence of a Method Definition Keyword:
- Java does not use dedicated declaration keywords like
function,func,method, ordefto define methods. - A method signature begins directly with optional modifiers, followed by the return type, the method identifier, and the parameter list.
- Java does not use dedicated declaration keywords like
Methods with a Return Value:
- A non-void method must specify a concrete return type (primitive or reference type) in its signature.
- It must contain an executable
returnstatement that supplies a value compatible with the declared return type along all possible execution paths.
Methods Without a Return Value (
void):- A method that does not return any value must use the
voidkeyword as its return type. - Valid syntax for declaring a non-returning method:
java void methodName() - Java does not possess keywords such as
noret. - Declaring a method as
null methodName()or omitting the return type entirely (e.g.,methodName()) is syntactically invalid. - Non-void methods cannot simply use
-1ornullimplicitly; the return type must be explicitly written in the method header.
- A method that does not return any value must use the
Instance Method Invocation:
Consider the class: ```java public class Point { private int x; private int y;
public String getInfo(){ return "Point at position [" + x + "," + y + "]"; } } ```
The method
getInfo()is an instance method (non-static) that returns aString.It must be invoked on an instantiated object variable using the dot operator:
point.getInfo().Invoking it statically via the class name (e.g.,
Point.getInfo()) causes a compile-time error because a non-static method cannot be referenced from a static context.The return value is in text form (
String), not numerical form.
Control Flow and Compiler Return Path Verification
The Missing Return Statement Error:
- If a method defines a return type other than
void, the Java compiler enforces that every reachable execution path terminates in a validreturnstatement returning the matching type. - Consider the following setter implementation:
java public boolean setX(int x){ if (x >= 0){ this.x = x; } } - This code is erroneous and fails to compile:
- It declares a return type of
boolean. - It contains no
returnstatement whatsoever. - Even if a
return true;were placed inside theifblock, execution paths wherex < 0would still lack a return value.
- If a method defines a return type other than
Conditional Branching and Return Paths:
- Consider the method:
java public boolean move(int dx, int dy){ if (x + dx >= 0 && y + dy >= 0){ x = x + dx; y += dy; return true; } } - This code will not function and fails compilation with the error:
missing return statement. - If the condition
(x + dx >= 0 && y + dy >= 0)evaluates tofalse, the execution bypasses theifblock, reaching the end of the method body without returning aboolean.
- Consider the method:
Corrective Action for Complete Return Coverage:
- To render the
movemethod fully functional, an explicit default return statement must be appended after theifblock:java public boolean move(int dx, int dy){ if (x + dx >= 0 && y + dy >= 0){ x = x + dx; y += dy; return true; } return false; }
- To render the
Adding
return false;after theifblock guarantees that every branch evaluates to a valid boolean value (trueon success,falseon condition failure).