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 class keyword, followed by the class identifier and the class body enclosed in curly braces: java [modifiers] class ClassName { // fields and methods }     
    • Placing the class keyword 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).
  • 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 Point encapsulating 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 new Keyword and Memory Allocation:

    • The new keyword is the dedicated operator used to dynamically allocate memory on the heap and instantiate an object in Java.
    • Keywords such as instance, object, or create do not exist for object creation in Java.
  • 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();     
  • 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(); or int point = new int(Point);) results in a compilation error due to type incompatibility.

  • Java is strictly case-sensitive; calling new point() instead of new Point() causes a compilation error because the identifier point does not match the class name Point.

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 x and y:
    • Declaration: Specifies the access level (private) and data type (int).
    • Initialization: Assigns an initial value (0) to each variable.
  • 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 this Keyword:

    • The this keyword 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;     
  • In this expression, this.x explicitly targets the instance variable of the current object, whereas x refers to the local method parameter.

  • The this keyword does not exist to define exceptions or handle conditional logic.

Access Modifiers and Encapsulation

  • The private Access Modifier:

    • To restrict access to an attribute or method exclusively to the enclosing class, the private modifier must be used.
    • Any attempt to access a private member 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.
  • Encapsulation Constraints on Direct Field Access:

    • Given the class declaration: java public class Point { private int x; private int y; }     
  • If an instance point is created in an external context: java Point point = new Point();     

  • Direct field access expressions such as point.x or point.y (e.g., System.out.println(point.x + " " + point.y);) fail to compile because x and y are marked private.

  • 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 private without 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, or def to define methods.
    • A method signature begins directly with optional modifiers, followed by the return type, the method identifier, and the parameter list.
  • 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 return statement 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 void keyword 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 -1 or null implicitly; the return type must be explicitly written in the method header.
  • 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 a String.

  • 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 valid return statement 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 return statement whatsoever.
    • Even if a return true; were placed inside the if block, execution paths where x < 0 would still lack a return value.
  • 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; } } &nbsp;&nbsp;&nbsp;&nbsp;
    • This code will not function and fails compilation with the error: missing return statement.
    • If the condition (x + dx >= 0 && y + dy >= 0) evaluates to false, the execution bypasses the if block, reaching the end of the method body without returning a boolean.
  • Corrective Action for Complete Return Coverage:

    • To render the move method fully functional, an explicit default return statement must be appended after the if block: java public boolean move(int dx, int dy){ if (x + dx >= 0 && y + dy >= 0){ x = x + dx; y += dy; return true; } return false; } &nbsp;&nbsp;&nbsp;&nbsp;
  • Adding return false; after the if block guarantees that every branch evaluates to a valid boolean value (true on success, false on condition failure).