Chapter 4.1: Objects and Classes

Object Oriented Programming with Java
Classes and objectsConstructorsKinds of fields and methodsstatic members Access and data hidingReferences and this== and equalsWrapper classes record and enumInner classesKinds of classes
Sercan KÜLCÜ · Giresun University · Computer Engineering

Introduction

Learning Outcomes

Classes and objects

Explain a class as a blueprint and an object as a concrete instance built from it; write a class with fields and methods.

Creating objects

Use the new operator and constructors; know default values and the default constructor.

Instance and class members

Tell instance members from static fields and methods; trace the order in which initializer blocks run.

References

Show with a memory diagram that a variable holds a reference, not the object; tell apart this, == and equals.

Constructor chaining and access

Chain constructors with this(...); explain the purpose of access modifiers and data hiding.

Special kinds of classes

Recognize wrapper classes, record, enum and inner classes; design a class from scratch with the Rational example.

Object-Oriented Programming

Object-Oriented Programming

  • Object-oriented programming (OOP) builds a program out of interacting objects.
  • An object represents a clearly identifiable entity in the real world: a student, a table, a circle, a button on screen, even a loan.
  • Every object has state (its data) and behavior (what it can do).
Analogy: a school works through student, teacher and course objects sending messages to one another (calling methods).
ObjectFields (state)Behavior
Studentname, id, deptenroll(), viewGrades()
Tablewidth, depth, materialmove()
Circlecenter, radiusarea(), perimeter()
Buttonlabel, color, enabledclick()
Loanamount, rate, terminstallment()

Object-Oriented Programming

Objects: Fields and Behavior

  • A class has members: fields, methods and constructors.
  • Objects store data: these pieces of data are called fields.
  • Objects perform operations: these operations are called behavior (methods).
  • Bundling data with the code that works on it makes a program more organized, reusable and intuitive.
student1 : Studentname = "Ali"id = 2012dept = "EEE"greet()addCourse(name, grade)average()← fields← behavior (methods)

Object-Oriented Programming

Procedural vs Object-Oriented

Procedural approachObject-oriented approach
Basic unitFunction (method)Object (data + methods)
DataIn separate variables; any function can access itInside the object; exposed in a controlled way
Examplearea(width, height)rect.area()
Large programsA change affects many functionsA change usually stays inside one class
ReuseBy copying functionsThrough classes and inheritance

The static-method programs we have written so far were procedural. In Java all code lives in a class; in OOP, classes are used to create objects.

Proceduralarea()perimeter()draw()width, height (data)Object-orientedrectw=5, h=3area() …squarew=4, h=4area() …

Object-Oriented Programming

Three Core Properties

Encapsulation

An object can hide its internal details from other objects. It acts like a closed box, used only through permitted methods.

Inheritance

A class can inherit the fields and methods of another class. This enables code reuse and class hierarchies.

Polymorphism

An object can take many forms (types); the same call behaves differently on different objects, giving flexibility and dynamic behavior.

A fourth is often added: abstraction, hiding needless detail and showing only the essential features.

Classes and Objects

Class: The Blueprint of an Object

  • A class is the blueprint of an object; one class can produce many objects carrying different data.
  • A class specifies the data (fields) an object holds and the operations (methods) it can perform.
  • An object is an instance of a class: its concrete form in memory.
  • Classes let us model real-world entities: a Car class can represent any automobile; each make and model is an object of that class.
Class (blueprint)Carbrandmodelyearcolordrive()stop()signal()newcar1 : CarToyota Corollacar2 : CarFord Mustangcar3 : CarFiat EgeaObjects (instances)

Analogy: the class is a cookie cutter; objects are the cookies cut with it.

Classes and Objects

Example: The Car Class

Fields (data)

Brand, Model, Year, Color

Methods (operations)

Drive, Stop, Signal

Two objects of the same class have the same field names but different values.

Car- brand : String- model : String- year : int- color : String+ drive() : void+ stop() : void+ signal() : voidcar1 : Carbrand = "Toyota"model = "Corolla"year = 2022color = "Gray"car2 : Carbrand = "Ford"model = "Mustang"year = 2023color = "Blue"instance of

UML class diagram: name / fields / methods; - private, + public. Object names are underlined.

Classes and Objects

Defining a Class

public class Car {
  // Fields
  String brand;
  String model;
  int year;
  String color;

  // Methods
  void drive() {
    System.out.println(brand + " is moving.");
  }

  void stop() {
    System.out.println(brand + " stopped.");
  }

  void signal() {
    System.out.println(brand + " is signaling.");
  }
}
  • The class keyword and the class name come first; the body goes between { }.
  • Class names start with a capital letter (Car, BankAccount); a public class must be in a file of the same name (Car.java).
  • Fields are declared in the class body, outside the methods; every method can use them directly.
  • The methods have no static: each belongs to a particular car (object).
  • This class has no main; it does not run on its own; another class uses it.

Classes and Objects

Using a Class

public class CarTest {
  public static void main(String[] args) {
    Car car1 = new Car();
    car1.brand = "Toyota";
    car1.model = "Corolla";
    car1.year = 2022;
    car1.color = "Gray";

    Car car2 = new Car();
    car2.brand = "Ford";
    car2.model = "Mustang";
    car2.year = 2023;
    car2.color = "Blue";

    car1.drive();
    car2.signal();
    car1.stop();
  }
}
Output
Toyota is moving.
Ford is signaling.
Toyota stopped.
  • new Car() creates an object; car1 refers to it.
  • car1.brand = "Toyota";: the dot (.) accesses a field of the object.
  • car1.drive(): the method works with car1's data; car2.signal() uses car2's.
  • Changing fields directly from outside like this is a bad habit; the right way is to use constructors and accessor methods.

Classes and Objects

Members of a Class

Fields

Represent the data objects can hold. Example: a Student class with name and surname.

Methods

Define the operations objects can perform. Example: a Dog class with bark() and run().

Access level

Each member can be private, protected, default (nothing written) or public: this decides who may use it.

Ownership

Each member can belong to the object (instance, the default) or, with static, belong to the class.

Constructors are also written inside the class, but they run only when an object is created and are technically a separate kind of member, not methods. A class can also contain other classes (inner classes).

Classes and Objects

Access Modifiers and Data Hiding

  • Access modifiers (public, protected, private; package access if none is written) specify who can reach a member from outside the class.
  • Rule of thumb: fields private, methods offered to others public.
  • A field's value is read by an accessor (getter, get...) and changed by a mutator (setter, set...); the setter rejects invalid values.
  • This arrangement is data hiding: only the class's own methods access its fields directly. It is the basis of encapsulation.
public class BankAccount {
  private double balance;   // hidden field
  public double getBalance() {
    return balance;
  }
  public void setBalance(double b) {
    if (b >= 0) balance = b;  // reject invalid
  }
}
// in another class:
acct.balance = -500;
error: balance has private access in BankAccount

Constructors

Constructors

  • A constructor is a special method; new calls it automatically when creating an object.
  • Its job is to give the fields their initial values and do any other setup.
  • Its name matches the class name (including case).
  • It has no return type, not even void; it cannot return a value.
  • Usually declared public; it can also be private to restrict object creation (e.g. the singleton pattern).
  • A class can have more than one constructor (with different parameters).
public class Student {
  private String name;
  private int id;

  // Constructor: class name, no return type
  public Student(String name, int id) {
    this.name = name;
    this.id = id;
  }
}

// Usage:
Student s = new Student("Ali", 2012);

Constructors

How Is an Object Created?

ClassName objectName = new ClassName(arguments);

Car corolla = new Car("Toyota", "Corolla", 2022);
Scanner in = new Scanner(System.in);
Book book = new Book();
import java.util.Scanner;
public class CreateDemo {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    StringBuilder text = new StringBuilder("Java");
    String title = "Objects";           // shortcut
    String author = new String("Sercan");  // long way
    text.append(" 21");
    System.out.println(text + " / " + title);
    System.out.println(author.length());
    System.out.println(in.nextInt() * 2);
  }
}

Shortcut: String title = "Objects"; creates a String object, whereas String title; only declares a reference.

  1. new reserves space on the heap for the object; fields get default values.
  2. A constructor is called and sets initial values.
  3. new evaluates to the object's reference, which is assigned to the variable.
Output
(input: 21)
Java 21 / Objects
6
42

Constructors

Constructor Example: Car

public class Car {
  private String model;
  private String color;

  public Car(String model, String color) {
    this.model = model;
    this.color = color;
  }

  public void printInfo() {
    System.out.println(model + " - " + color);
  }

}
public static void main(String[] args) {
  Car sportsCar = new Car("2022", "RED");
  Car classicCar = new Car("2023", "WHITE");
  sportsCar.printInfo();
  classicCar.printInfo();
}
StackHeapmain()sportsCarclassicCarCar objectmodel"2022"color"RED"Car objectmodel"2023"color"WHITE"
Output
2022 - RED
2023 - WHITE

Constructors

References

  • An object cannot be used directly; it is reached only through a reference. Variables store the object's reference, not the object itself.
  • A reference can be thought of as an address telling where the object is in memory.
  • int, double, boolean and other primitive variables hold the value itself; class-type variables (Car, String, Scanner) hold a reference.
  • A reference that points to no object has the value null.
Analogy: the variable is a TV remote; the object is the TV. Copying the remote does not create a second TV.
StackHeapmain()sportsCarclassicCarnewCarnullCar objectmodel"2022"color"RED"Car objectmodel"2023"color"WHITE"

Local variables live on the stack, objects on the heap; arrow = reference.

Constructors · Step-by-step code trace

new Car(...): Step by Step

StackHeapmain()sportsCar?classicCar?Car #1modelnullcolornull

new allocates a new object on the heap; String fields first get the default value null.

StackHeapCar(...)thismodel"2022"color"RED"main()sportsCar?classicCar?Car #1modelnullcolornull

The constructor is called: parameters receive copies of the arguments; this refers to the new object.

StackHeapCar(...)thismodel"2022"color"RED"main()sportsCar?classicCar?Car #1model"2022"colornull

this.model = model: the left side is the object's field, the right side the parameter.

StackHeapCar(...)thismodel"2022"color"RED"main()sportsCar?classicCar?Car #1model"2022"color"RED"

this.color = color: the object is now ready.

StackHeapmain()sportsCarclassicCar?Car #1model"2022"color"RED"

The constructor returns and its frame is removed. The new expression yields a reference, which is stored in sportsCar.

StackHeapmain()sportsCarclassicCarCar #1model"2022"color"RED"Car #2model"2023"color"WHITE"

Same steps again: a separate object is created, with its own model and color copies.

StackHeapprintInfo()thismain()sportsCarclassicCarCar #1model"2022"color"RED"Car #2model"2023"color"WHITE"

sportsCar.printInfo(): inside the method, this = #1, so #1's fields are printed.

StackHeapprintInfo()thismain()sportsCarclassicCarCar #1model"2022"color"RED"Car #2model"2023"color"WHITE"

Same method, but now this = #2. The code is shared; the data is separate per object.

public class Car {
  private String model;
  private String color;

  public Car(String model, String color) {
    this.model = model;
    this.color = color;
  }

  public void printInfo() {
    System.out.println(model + " - " + color);
  }

  public static void main(String[] args) {
    Car sportsCar = new Car("2022", "RED");
    Car classicCar = new Car("2023", "WHITE");
    sportsCar.printInfo();
    classicCar.printInfo();
  }
}

Constructors

Default Constructor

  • If a class declares no constructor, the compiler adds the default constructor: no parameters, empty body. Creating an object always calls some constructor.
  • Uninitialized fields get a default value (local variables do not):
Field typeDefault value
byte short int long0
float double0.0
booleanfalse
char'\u0000' (code 0)
Reference (String, arrays, objects)null
class Point3 {
  int x;
  double weight;
  boolean visible;
  char letter;
  String name;
}
public class Defaults {
  public static void main(String[] args) {
    Point3 p = new Point3();   // default constructor
    System.out.println(p.x + " " + p.weight);
    System.out.println(p.visible + " " + p.name);
    System.out.println((int) p.letter);
  }
}
Output
0 0.0
false null
0

Constructors

No-Arg and Parameterized Constructors

public class Vehicle {
  private String brand;
  private String model;
  private int year;
  public Vehicle() {                 // no-arg constructor
    brand = "Unknown";
    model = "Unknown";
    year = 0;
  }
  public Vehicle(String brand, String model, int year) {
    this.brand = brand;
    this.model = model;
    this.year = year;
  }
  public void printInfo() {
    System.out.println(brand + " " + model + " " + year);
  }
  public static void main(String[] args) {
    Vehicle v1 = new Vehicle();
    Vehicle v2 = new Vehicle("Renault", "Clio", 2021);
    v1.printInfo();
    v2.printInfo();
  }
}
Output
Unknown Unknown 0
Renault Clio 2021
  • Vehicle() is our own no-arg constructor; it sets the fields to meaningful initial values.
  • The two constructors share a name but differ in parameters: constructor overloading. The arguments decide which one runs.
  • Once a class has any constructor, the compiler no longer adds the default one. If only a parameterized constructor exists, new Vehicle() does not compile: constructor Vehicle in class Vehicle cannot be applied to given types.

Fields

Fields and Their Kinds

Fields are data variables declared inside the class (outside any method). There are two basic kinds:

Instance fieldClass field (static)
Declarationprivate String name;private static int accountCount;
CopiesEach object has a separate copyA single copy in the class, shared by all objects
Created when?With every newOnce, when the class is loaded
Accessobj.nameClassName.accountCount
ExampleStudent: name, surnameBankAccount: accountCount
  • Constant (final) fields get a value once and cannot change afterwards. Class constants are usually static final and written in UPPER_CASE: Math.PI.
  • Static initializers (static { }) run once, when the class loads; instance initializers ({ }) run every time an object is created.

Fields · Step-by-step code trace

static Counter: Step by Step

StackHeapClass area (static): BankAccountaccountCount0

When the class loads, the static field is created once and set to 0. No objects exist yet.

StackHeapClass area (static): BankAccountaccountCount1constructorthismain()h1?h2?h3?BankAccount #1owner"Ali"

First object: its own owner copy becomes "Ali"; the shared counter goes up to 1.

StackHeapClass area (static): BankAccountaccountCount1main()h1h2?h3?BankAccount #1owner"Ali"

h1 refers to the first object.

StackHeapClass area (static): BankAccountaccountCount2main()h1h2h3?BankAccount #1owner"Ali"BankAccount #2owner"Ayşe"

The second object has its own separate owner field, but the counter is the same field: 2.

StackHeapClass area (static): BankAccountaccountCount3main()h1h2h3BankAccount #1owner"Ali"BankAccount #2owner"Ayşe"BankAccount #3owner"Can"

Three objects, three owner fields, but a single accountCount = 3.

StackHeapClass area (static): BankAccountaccountCount3main()h1h2h3BankAccount #1owner"Ali"BankAccount #2owner"Ayşe"BankAccount #3owner"Can"

h2.owner: an instance field is read through the object.

StackHeapClass area (static): BankAccountaccountCount3static methodmain()h1h2h3BankAccount #1owner"Ali"BankAccount #2owner"Ayşe"BankAccount #3owner"Can"

static methods are called via the class name; there is no this here, so it reads only the static field.

StackHeapClass area (static): BankAccountaccountCount3main()h1h2h3count3BankAccount #1owner"Ali"BankAccount #2owner"Ayşe"BankAccount #3owner"Can"

The returned 3 goes into count and is printed.

public class BankAccount {
  private String owner;
  private static int accountCount = 0;

  public BankAccount(String owner) {
    this.owner = owner;
    accountCount++;
  }

  public static int getAccountCount() {
    return accountCount;
  }

  public static void main(String[] args) {
    BankAccount h1 = new BankAccount("Ali");
    BankAccount h2 = new BankAccount("Ayşe");
    BankAccount h3 = new BankAccount("Can");
    System.out.println(h2.owner);
    int count = BankAccount.getAccountCount();
    System.out.println(count);
  }
}

Fields

Field Declarations

public class Book {
  // Instance fields
  private String title;
  private String author;
  private int pageCount;
  // Class field
  private static int bookCount;
  // a final field (constant)
  public static final double PI = 3.14159265359;
}
public class Fields {
  public int a;                         // public
  int b = 1, c = 2;                     // default (package)
  private double x;                     // private
  private static int xx;                // static, private
  public static int y;                  // static, public
  public final int CONST1 = 5;          // cannot change
  private static final int CONST2 = 6;  // static constant
}
  • Syntax: [access] [static] [final] type name [= initValue];
  • Several fields on one line: int b = 1, c = 2;
  • PI is defined here as an example; Java has a ready-made constant: Math.PI.
  • final fields cannot be reassigned; doing so is a compile error:
    error: cannot assign a value to final variable CONST1

Fields

Initializer Blocks

Static initializer

The static { ... } block runs when the class is first loaded, and only once. It initializes complex static fields.

Instance initializer

The { ... } block runs every time an object is created, just before the constructor body. It holds work common to all constructors.

Order when creating an object: (1) on first use of the class, static fields and static blocks → (2) new allocates memory, fields get default values → (3) field initializers and instance initializer blocks (in source order) → (4) the constructor body.

Dog has both. Note: the value bark() returns is not printed; with System.out.println(d2.bark()); the last line would be "Gece woof woof!".

1 static { } and static fieldsonce, on first use of the class2 new: memory allocatedfields at default values3 field initializers, { }in source order, every new4 constructor bodyevery new

Fields · Step-by-step code trace

Dog: Initializer Order

StackHeapDog class loadedstatic block"ran"

main runs only after the class is loaded: the static block runs once. (var, Java 10+: infers the type from the right side; String... = String[].)

StackHeapmain()d1?d2?Dog #1namenull

new Dog("Kara"): space is allocated for the object, name = null.

StackHeapDog(name)thisname"Kara"main()d1?d2?Dog #1namenull

The instance initializer runs before the constructor body.

StackHeapDog(name)thisname"Kara"main()d1?d2?Dog #1name"Kara"

Now the constructor body: this.name = name.

StackHeapDog(name)thisname"Kara"main()d1?d2?Dog #1name"Kara"

The constructor prints the name: Kara.

StackHeapmain()d1d2Dog #1name"Kara"Dog #2name"Gece"

Second object: initializer + constructor again; the static block does not run again.

StackHeapbark()thismain()d1d2Dog #1name"Kara"Dog #2name"Gece"

bark() returns a string, but the value is unused: nothing is printed.

public class Dog {
  String name;                 // field
  Dog(String name) {         // constructor
    this.name = name;
    System.out.println(name);
  }
  String bark() {            // instance method
    return name + " woof woof!";
  }
  static {                    // static initializer
    System.out.println("Dogs!");
  }
  {                           // instance initializer
    System.out.println("Creating a dog.");
  }
  public static void main(String... strings) {
    var d1 = new Dog("Kara");
    var d2 = new Dog("Gece");
    d2.bark();
  }
}

Methods

Kinds of Methods

  • Methods are blocks of code in a class that do a specific job; they define the class's behavior.
  • Instance methods are tied to an object: phone.call(...). They use that object's fields.
  • Class methods (static) belong to the class itself and are shared by all objects: called through Phone.
  • Static methods belong to no particular object, so instance data (such as model) cannot be accessed directly.
public class Phone {
  private String model;
  private static String osVersion = "Version 1";

  // Instance method
  public void call(String number) {
    System.out.println(model + " calling: " + number);
  }

  // Instance method
  public void sendMessage(String to, String msg) {
    System.out.println(to + " <- " + msg);
  }

  // Class method (static)
  public static void updateOS(String newVersion) {
    osVersion = newVersion;
  }
}

Methods

Method Example: Email

public class Email {
  public boolean send(String to, String subject,
             String body) {
    // a simulation, not a real send
    if (to == null || !to.contains("@")) {
      return false;               // failed
    }
    System.out.println(to + " <- " + subject);
    return true;                    // succeeded
  }

  public static void main(String[] args) {
    Email e = new Email();
    boolean s1 = e.send("ali@example.com", "Homework", "Hi");
    boolean s2 = e.send("ali.example.com", "Homework", "Hi");
    System.out.println(s1 + " " + s2);
  }
}
The send method
  • Name: send
  • Parameters: three Strings: to, subject, body
  • Return type: boolean: was the send successful?
Output
ali@example.com <- Homework
true false

boolean methods: every path must end in a return; a method whose body is only a comment gives a missing return statement error.

Methods

Instance Fields and Methods

  • Declared in the class without the static keyword.
  • Every object has its own copy of the fields, so objects can hold different data.
  • Fields represent the object's properties; methods, its behavior.
  • To use them, first create an object: new, then obj.method().
  • The method code is shared by all objects; on each call this decides whose data it uses.
Instancestatic
Belongs to?ObjectClass
Callobj.method()ClassName.method()
Needs an object?YesNo
this available?YesNo
Examplestr.length()Math.sqrt(x)
greet() codeone copy in the classstudent1 objectname = "Ali"thisstudent2 objectname = "Ayşe"this

Methods

The Dot Operator

public class Phone {
  String number;
  public Phone(String number) {
    this.number = number;
  }
  public void call(Phone phone) {
    System.out.println(number + " calling: " + phone.number);
  }
  public void sendMessage(Phone phone, String msg) {
    System.out.println(phone.number + " <- " + msg);
  }
  public void openCamera() {
    System.out.println(number + " opened the camera.");
  }
  public static void main(String[] args) {
    Phone phone1 = new Phone("5551234567");
    Phone phone2 = new Phone("5051234567");
    phone1.call(phone2);
    phone2.sendMessage(phone1, "Hello!");
    phone1.openCamera();
  }
}
Output
5551234567 calling: 5051234567
5551234567 <- Hello!
5551234567 opened the camera.
  • Once an object exists, its fields and methods are reached with the dot operator: obj.method(...), obj.field.
  • phone1.call(...): phone1 places the call; in the method, number is phone1's and phone.number is phone2's number.
  • An object can take another object as a parameter.

Methods

The Rectangle Class

public class Rectangle {
  private double length;     // rectangle's length
  private double width;    // rectangle's width

  // Constructor
  public Rectangle(double length, double width) {
    this.length = length;
    this.width = width;
  }

  public double area() {      // computes the area
    return length * width;
  }

  public double perimeter() {     // computes the perimeter
    return 2 * (length + width);
  }
}
  • Fields are private: used from outside only through methods.
  • The constructor takes the two sides and stores them in the object.
  • area() and perimeter() take no parameters: the data they need is inside the object.
  • The procedural version would be area(5.0, 3.0); with an object it is rect.area().

Methods · Step-by-step code trace

Rectangle: Step by Step

StackHeapmain()rectsquarearea?perimeter?Rectangle #1length5.0width3.0Rectangle #2length5.0width5.0

Two objects, each with its own length and width values.

StackHeaparea()thismain()rectsquarearea?perimeter?Rectangle #1length5.0width3.0Rectangle #2length5.0width5.0

rect.area(): this = #1, result 5.0 × 3.0 = 15.0.

StackHeapperim...()thismain()rectsquarearea15.0perimeter?Rectangle #1length5.0width3.0Rectangle #2length5.0width5.0

area = 15.0. perimeter(): 2 × (5.0 + 3.0) = 16.0.

StackHeapmain()rectsquarearea15.0perimeter16.0Rectangle #1length5.0width3.0Rectangle #2length5.0width5.0

double values print as 15.0.

StackHeaparea()thismain()rectsquarearea25.0perimeter20.0Rectangle #1length5.0width3.0Rectangle #2length5.0width5.0

Same methods, but now this = #2 (square): 25.0 and 20.0. The old values are overwritten.

StackHeapmain()rectsquarearea25.0perimeter20.0Rectangle #1length5.0width3.0Rectangle #2length5.0width5.0

The second line is printed. A long statement can span two lines; it lasts until the ;.

public class RectangleTest {
  public static void main(String[] args) {
    Rectangle rect = new Rectangle(5.0, 3.0);
    Rectangle square = new Rectangle(5.0, 5.0);
    double area = rect.area();
    double perimeter = rect.perimeter();
    System.out.println("Area: " + area
        + " Perimeter: " + perimeter);
    area = square.area();
    perimeter = square.perimeter();
    System.out.println("Area: " + area
        + " Perimeter: " + perimeter);
  }
}

static Members

static Variables and Methods

public class MathUtil {
  // Static add method
  public static int add(int a, int b) {
    return a + b;
  }

  public static void main(String[] args) {
    int result = MathUtil.add(5, 3);
    System.out.println("Sum: " + result);
    System.out.println(Math.max(4, 9));
    System.out.println(Math.sqrt(16.0));
  }
}
  • static members belong to the class.
  • To access static members you need no object; use the class name and a dot: ClassName.fieldName, ClassName.methodName(args).
  • They can also be reached through an object (obj.fieldName), but this is discouraged: readers will think the member belongs to the object.
  • Built-in examples: Math.max(), Math.sqrt(), Math.PI, Integer.parseInt() and main.
Output
Sum: 8
9
4.0

static Members

static Rules

From →Using instance field/methodUsing static field/method
From an instance method✓ directly (name, this.name)✓ directly
static method (main included)✗ only through an object (s.name)✓ directly
public class Greeter {
  private String name = "Ali";
  public void greet() {
    System.out.println("Hello " + name);
  }
  public static void main(String[] args) {
    greet();
  }
}
error: non-static method greet() cannot be referenced from a static context
public class Greeter2 {
  private String name = "Ali";
  public static void print() {
    System.out.println(name);
  }
}
error: non-static variable name cannot be referenced from a static context

Fix: call it through an object (new Greeter().greet();) or make the method static.

References and this

Reference Assignment

  • In Java, objects are handled through references (addresses).
  • car2 = car1; does not copy the object, only the reference: both variables point to the same object (an alias).
  • A change made through one is visible through the other.
Library labelThe label on the shelf is not the book itself; it shows where it is.
Car keyA key points to a car; two keys open the same car.
public class Car {
  private String brand;

  public Car(String brand) {
    this.brand = brand;
  }

  public String getBrand() {
    return brand;
  }

  public void setBrand(String brand) {
    this.brand = brand;
  }

}

References and this · Step-by-step code trace

Reference Assignment: Step by Step

StackHeapmain()car1car2?Car #1brand"Toyota"

An object is created; car1 refers to it.

StackHeapmain()car1car2Car #1brand"Toyota"

car2 = car1: the reference is copied. There is still a single object.

StackHeapmain()car1car2Car #1brand"Toyota"

Both variables read the same object: both say Toyota.

StackHeapsetBrand()thisbrand"Ford"main()car1car2Car #1brand"Ford"

car2.setBrand("Ford") changes the shared object.

StackHeapmain()car1car2Car #1brand"Ford"

car1 now reads Ford too: the change is shared.

StackHeapmain()car1nullcar2Car #1brand"Ford"

car1 = null: only this variable lets go; the object is not deleted, and car2 still refers to it.

StackHeapmain()car1nullcar2Car #1brand"Ford"

When the last reference to an object is gone, the garbage collector removes it.

public static void main(String[] args) {
  Car car1 = new Car("Toyota");
  Car car2 = car1;
  System.out.println("Car 1: " + car1.getBrand());
  System.out.println("Car 2: " + car2.getBrand());
  car2.setBrand("Ford");
  System.out.println("Car 1: " + car1.getBrand());
  car1 = null;
  System.out.println("Car 2: " + car2.getBrand());
}

References and this

null and NullPointerException

public class Empty {
  String name;

  public static void main(String[] args) {
    Empty b = null;
    System.out.println(b.name.length());
  }
}
Exception in thread "main" java.lang.NullPointerException: Cannot read field "name" because "<local1>" is null
    at Empty.main(Empty.java:6)

If a local variable is used before it gets a value, the program does not compile: error: variable sb might not have been initialized

  • null means the reference variable points to no object.
  • null references: reading a field or calling a method through one throws NullPointerException at run time.
  • Prevention: check before use: if (b != null) { ... }
  • Objects that no reference points to are removed automatically by the JVM's garbage collector; in Java you never delete objects by hand.
main()bnullb.name→ NullPointerExceptionobject with no referencesgarbage collector removes it

References and this

The this Keyword

public class Shadow {
  private String name;

  public Shadow(String name) {
    name = name;            // forgot this!
  }

  public static void main(String[] args) {
    Shadow g = new Shadow("Ali");
    System.out.println(g.name);
  }
}
Output
null
  • this is a reference to the object the method was called on.
  • static methods cannot use it (there is no object there).
  • Most often used in constructors, when the field and the parameter have the same name: this.name = name;
  • The code on the left forgot this: name = name; assigns the parameter to itself, and the field stays null. The compiler reports no error!
  • this(...), by contrast, calls another constructor of the same class.
Shadow("Ali") framename"Ali"thisname = nameparameter to itselfShadow objectnamenullwith this.name = name, "Ali" would land here

References and this

Passing the Object with this

public class Team {
  private String name;
  public Team(String name) {
    this.name = name;
  }
  public void addPlayer(Player player) {
    player.joinTeam(this);   // this object
  }
  public String getName() {
    return name;
  }
  public static void main(String[] args) {
    Team team = new Team("Giresunspor");
    Player player = new Player("Mert");
    team.addPlayer(player);
  }
}
  • this passes the current object to another method as a parameter.
  • team.addPlayer(player) runs with this = team; joinTeam(this) hands it to the player.
  • A second class in the same file (not public):
class Player {
  private String name;
  Player(String name) {
    this.name = name;
  }
  void joinTeam(Team team) {
    String t = team.getName();
    System.out.println(name + " -> " + t);
  }
}
Output
Mert -> Giresunspor

References and this · Step-by-step code trace

Greeting with this: Step by Step

StackHeapStudent(name)thisname"Ali"main()student1?student2?Student #1name"Ali"

In the constructor, this is the new object: this.name (field) = name (parameter).

StackHeapmain()student1student2Student #1name"Ali"Student #2name"Ayşe"

The second object is built by the same constructor; at that time this was #2.

StackHeapgreet()thismain()student1student2Student #1name"Ali"Student #2name"Ayşe"

student1.greet(): the object left of the dot becomes this → "Ali".

StackHeapgreet()thismain()student1student2Student #1name"Ali"Student #2name"Ayşe"

Same code, different this → "Ayşe". Here this.name and name do the same thing.

public class Student {
  private String name;

  public Student(String name) {
    this.name = name;
  }

  public void greet() {
    System.out.println("Hi, I am " + this.name);
  }

  public static void main(String[] args) {
    Student student1 = new Student("Ali");
    Student student2 = new Student("Ayşe");
    student1.greet();
    student2.greet();
  }
}

References and this

this(...) and Constructor Chaining

  • this(...) calls another constructor of the same class. Shared initialization lives in one constructor; the others delegate to it, supplying the missing arguments.
  • this(...) must be the first statement of the constructor; placed after another statement, it does not compile.
  • The called constructor's body finishes first, then the caller's remaining lines run; however long the chain, only one object is built.
  • If constructors call each other in a cycle, the compiler catches it.
class Employee {
  private String name;
  private double salary;
  Employee(String name) {
    this(name, 20000.0);   // same-class constructor
  }
  Employee(String name, double salary) {
    this.name = name;        // init in one place
    this.salary = salary;
  }
}

Not on the first line: A() { x = 1; this(2); }

error: call to this must be first statement in constructor

Cycle: A() { this(1); } and A(int x) { this(); }

error: recursive constructor invocation

References and this · Step-by-step code trace

new Book("Nutuk", "Atatürk"): Step by Step

StackHeapmain()k2?Book objectnamenullauthornullpageCount0

new allocates a new object on the heap; fields get default values: null, null, 0.

StackHeapBook(name, author)thisname"Nutuk"author"Atatürk"main()k2?Book objectnamenullauthornullpageCount0

The arguments are two String values, so the two-parameter constructor runs. this points to the new object.

StackHeapBook(name)thisname"Nutuk"Book(name, author)thisname"Nutuk"author"Atatürk"main()k2?Book objectnamenullauthornullpageCount0

this(name): chaining. The one-parameter constructor is called for the same object.

StackHeapBook(name)thisname"Nutuk"Book(name, author)thisname"Nutuk"author"Atatürk"main()k2?Book objectname"Nutuk"authornullpageCount0

this.name = name: the parameter's value is written to the object's name field.

StackHeapBook(name, author)thisname"Nutuk"author"Atatürk"main()k2?Book objectname"Nutuk"author"Atatürk"pageCount0

Inner constructor done. Remaining line: this.author = author.

StackHeapmain()k2Book objectname"Nutuk"author"Atatürk"pageCount0

Constructors done; the new expression evaluates to the object's reference. k2 now refers to the object.

StackHeapmain()k2Book objectname"Nutuk"author"Atatürk"pageCount0

The dot operator reads the fields: Nutuk / Atatürk / 0.

class Book {
  String name;
  String author;
  int pageCount;
  public Book(String name) {
    this.name = name;
  }
  public Book(String name, String author) {
    this(name);  // constructor chaining
    this.author = author;
  }
}
// in main:
Book k2 = new Book("Nutuk", "Atatürk");
System.out.println(k2.name + " / "
    + k2.author + " / " + k2.pageCount);

Comparing Objects

== and equals()

  • Variables store only references to objects.
  • == compares memory addresses, not fields: do both variables point to the same object?
  • Content equality of two objects is checked with equals(), which compares all properties; in our own classes it must be overridden.
  • String and wrappers are objects too: for "Java" read from the keyboard and the literal "Java", == gives false, equals gives true.
  • equals, hashCode, toString and getClass come to every class from Object; when equals is overridden, hashCode must be too.
StackHeapmain()k1k2k3Person #1name"Ali"age20Person #2name"Ali"age20
ExpressionResult
k1 == k3true: same object
k1 == k2false: different objects
k1.equals(k2)true: same content*

* equals if overridden; otherwise Object's version behaves like ==.

Wrapper Classes

Wrapper Classes

Primitive typeWrapper class
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
charCharacter
booleanBoolean
  • Wrapper classes represent primitive types as objects.
  • Some places require an object: generic collections such as ArrayList<Integer> cannot hold primitives.
  • A primitive cannot hold null; a wrapper variable can ("no value").
  • Helper methods are provided: Integer.parseInt("12"), Integer.MAX_VALUE, Character.isDigit(c).
  • Primitives are faster and use less memory; prefer them unless an object is needed.
  • Autoboxing and unboxing conversions need care.
StackHeapint num42Integer wInteger objectvalue = 42the value itselfw may also be null

Wrapper Classes

Autoboxing and Unboxing

public class Wrappers {
  public static void main(String[] args) {
    // an int variable
    int num = 42;
    // using the Integer wrapper
    Integer w1 = Integer.valueOf(num);
    // Autoboxing (automatic)
    Integer w2 = num;
    // Unboxing (explicit and automatic)
    int n2 = w2.intValue();
    int n3 = w2;
    System.out.println(n2 + n3);
    System.out.println(w1.equals(w2));
    System.out.println(Integer.parseInt("123") + 1);
    System.out.println(Integer.MAX_VALUE);
    System.out.println(Character.isDigit('7'));
    System.out.println(Double.parseDouble("2.5") * 2);
    Integer empty = null; // an int can't be null
    System.out.println(empty);
  }
}
  • Autoboxing: primitive → wrapper, automatically. Unboxing: wrapper → primitive.
  • Explicit forms: Integer.valueOf(num), w.intValue().
Output
84
true
124
2147483647
true
5.0
null

Wrapper Classes

Wrapper Pitfalls

import java.util.ArrayList;
public class Pitfalls {
  public static void main(String[] args) {
    ArrayList<Integer> list = new ArrayList<>();
    list.add(5);                 // autoboxing: 5 -> Integer
    int first = list.get(0);       // unboxing: Integer -> int
    System.out.println(first + 1);
    Integer a = 127, b = 127;
    Integer c = 128, d = 128;
    System.out.println(a == b);
    System.out.println(c == d);
    System.out.println(c.equals(d));
    Integer empty = null;
    int x = empty;                  // NullPointerException
  }
}
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.Integer.intValue()" because "<local7>" is null
Output
6
true
false
true
  • Comparing wrapper objects with == is wrong: == compares references. Values from −128 to 127 come from a cache as the same object; for 128 the result is false.
  • Always compare with equals().
  • null wrapper: unboxing it throws NullPointerException at run time.

Wrapper Classes · Step-by-step code trace

Integer Cache: Code Trace

StackHeapmain()abcache: 127value127

Autoboxing calls Integer.valueOf(127). Values from −128 to 127 are cached in advance: a and b get the same object.

StackHeapmain()abcdcache: 127value127Integer #1value128Integer #2value128

128 is outside the cache range: valueOf creates a new object every time.

StackHeapmain()abcdcache: 127value127Integer #1value128Integer #2value128a == b → true (same object)

== compares references; both arrows reach the same object: true.

StackHeapmain()abcdcache: 127value127Integer #1value128Integer #2value128c == d → false (#1 ≠ #2)

Same value (128), different objects: false. This is the trap of comparing wrappers with ==.

StackHeapmain()abcdcache: 127value127Integer #1value128Integer #2value128c.equals(d) → 128 == 128 → true

Integer.equals compares the wrapped int values: true.

StackHeapmain()abcdt256cache: 127value127Integer #1value128Integer #2value128c.intValue() + d.intValue() = 256

+ does not work on objects: both are unboxed (intValue()). t is a primitive int; its value lives on the stack.

StackHeapmain()abcdt256cache: 127value127Integer #1value128Integer #2value128

The primitive t is printed directly: 256.

StackHeapmain()abcdt256emptynullcache: 127value127Integer #1value128Integer #2value128

A wrapper variable can hold null; int empty = null would not compile.

StackHeapmain()abcdt256emptynullx?cache: 127value127Integer #1value128Integer #2value128empty.intValue() → NullPointerException

int x = empty silently becomes empty.intValue(). There is no object behind it: NullPointerException, and the program stops.

Integer a = 127, b = 127;
Integer c = 128, d = 128;
System.out.println(a == b);
System.out.println(c == d);
System.out.println(c.equals(d));
int t = c + d;
System.out.println(t);
Integer empty = null;
int x = empty;

Records and enum

Records

  • A record (Java 16+) is a kind of class for writing data-only classes concisely.
  • Immutable objects: all fields are private final; there are no setters.
  • The compiler generates: a constructor, accessors x() and y() (names do not start with get), equals, hashCode, toString.
record Point(double x, double y) { }

This single line equals a roughly 30-line class with two fields, a constructor, two accessors and three Object methods.

public class RecordTest {
  public static void main(String[] args) {
    Point p1 = new Point(1.0, 2.5);
    Point p2 = new Point(1.0, 2.5);
    boolean same = p1.equals(p2);
    System.out.println(same);
    System.out.println(p1 == p2);
    System.out.println(p1);
    System.out.println(p1.x() + p1.y());
  }
}
Output
true
false
Point[x=1.0, y=2.5]
3.5
p.x = 3.0;   →   error: x has private access in Point

Records and enum

enum (Enumerated Type)

enum Weekday {
  MONDAY, TUESDAY, WEDNESDAY, THURSDAY,
  FRIDAY, SATURDAY, SUNDAY
}
public class DayTest {
  public static void main(String[] args) {
    Weekday[] allDays = Weekday.values();
    Weekday thu = Weekday.valueOf("THURSDAY");
    System.out.println(allDays.length + " days");
    System.out.println(thu + " " + thu.ordinal());
    for (Weekday day : allDays) {
      boolean weekend = day == Weekday.SATURDAY
          || day == Weekday.SUNDAY;
      if (weekend) {
        System.out.println(day + ": weekend");
      }
    }
  }
}
Output
7 days
THURSDAY 3
SATURDAY: weekend
SUNDAY: weekend
  • enum is a special type for a fixed, limited set of values.
  • values() returns all values as an array; you can loop over it.
  • valueOf converts text to a value; ordinal() gives the 0-based position. Values are compared with ==.

Inner Classes

Inner Classes

  • An inner class is a class defined inside another class. It can access the outer class's fields and methods directly (private ones included).
  • Used to group helper classes that serve only one class; very common for event listener classes in GUIs.
KindDefined where?Created how?
static inner classIn the class body, marked staticWithout an outer object: new Outer.StaticInner()
Member inner classIn the class body, without staticThrough an outer object: outer.new MemberInner()
Local inner classInside a methodOnly from inside that method
Anonymous inner classInside an expression, unnamedOne object where it is defined; implements an interface or abstract class

Inner Classes

static Inner Class

public class Outer {
  // a static inner class inside Outer
  static class StaticInner {
    void display() {
      System.out.println("Static Inner Class");
    }
  }

  public static void main(String[] args) {
    // access without an Outer instance
    Outer.StaticInner staticInner = new Outer.StaticInner();
    staticInner.display();
  }
}
Output
Static Inner Class
  • static appears in its declaration.
  • Can be created without an object of the outer class: new Outer.StaticInner().
  • It can directly access only the static members of the outer class.

Inner Classes

Member Inner Class

public class Outer {
  private int count = 5;          // outer's private field

  class MemberInner {            // member inner class
    void display() {
      System.out.println("Member Inner Class, count = " + count);
    }
  }

  public static void main(String[] args) {
    // access via an Outer instance
    Outer outer = new Outer();
    Outer.MemberInner memberInner = outer.new MemberInner();
    memberInner.display();
  }
}
Output
Member Inner Class, count = 5
  • Declared as a member of the outer class (no static).
  • Each member inner class object is bound to an outer object: outer.new MemberInner(). That is why it can read private count.
  • In main, a plain new MemberInner() does not compile:
error: non-static variable this cannot be referenced from a static context

Inner Classes · Step-by-step code trace

Member Inner Class: Code Trace

StackHeapmain()o1Outer #1count5

First outer object: its own count field is 5.

StackHeapmain()o1o2Outer #1count5Outer #2count5

Second outer object; it also starts at 5. There are two separate count fields.

StackHeapmain()o1o2Outer #1count5Outer #2count8

main is also inside Outer, so it can write the private field: only #2 changes.

StackHeapmain()o1o2mOuter #1count5Outer #2count8MemberInner #3Outer.this

o2.new MemberInner(): the inner object keeps a reference to the outer object that created it in a hidden field (Outer.this).

StackHeapdisplay()thismain()o1o2mOuter #1count5Outer #2count8MemberInner #3Outer.this

m.display(): inside the method, this is the inner object (#3). The inner class has no count field of its own.

StackHeapdisplay()thismain()o1o2mOuter #1count5Outer #2count8MemberInner #3Outer.thiscount = Outer.this.count = 8

count means Outer.this.count: the arrow goes to #2, so 8 is printed. With o1.new MemberInner() it would print 5.

public class Outer {
    private int count = 5;
    class MemberInner {
        void display() {
            System.out.println("count = " + count);
        }
    }
    public static void main(String[] args) {
        Outer o1 = new Outer();
        Outer o2 = new Outer();
        o2.count = 8;
        Outer.MemberInner m = o2.new MemberInner();
        m.display();
    }
}

Inner Classes

Local Inner Class

public class Outer {
  void outerMethod() {
    class LocalInner {         // defined inside the method
      void display() {
        System.out.println("Local Inner Class");
      }
    }
    // usable only inside this method
    LocalInner localInner = new LocalInner();
    localInner.display();
  }

  public static void main(String[] args) {
    Outer outer = new Outer();
    outer.outerMethod();
  }
}
Output
Local Inner Class
  • Defined inside a method; usable only from within that method.
  • Outside the method, the name LocalInner is unknown.
  • Used for a small helper type needed several times within one method.

Inner Classes

Anonymous Inner Class

interface MyInterface {
  void myMethod();
}

public class Outer {
  public static void main(String[] args) {
    // usually implements an interface or abstract class
    MyInterface myInterface = new MyInterface() {
      @Override
      public void myMethod() {
        System.out.println("Anonymous Inner Class");
      }
    };
    myInterface.myMethod();
  }
}
Output
Anonymous Inner Class
  • A class with no name; a single object is created where it is defined.
  • It usually implements an interface or an abstract class: new InterfaceName() { ... }; The trailing ; belongs to the assignment statement.
  • For single-method interfaces, a Java 8+ lambda is shorter: () -> ...

Kinds of Classes and Design

Classes and Types

interface Printable { ... }
interface Runner { ... }
class Animal implements Printable, Serializable { ... }
class Dog extends Animal implements Runner { ... }
var winner = new Dog(...);
  • An object belongs to exactly one class, but it can have many types.
  • winner belongs only to the Dog class.
  • Yet its types are: Dog, Runner, Animal, Printable, Serializable, Object; for all of them instanceof gives true.
  • This is the basis of polymorphism.
Object«interface»Printable«interface»SerializableAnimal«interface»RunnerDogextendsextends

Solid line + hollow triangle: inheritance (extends); dashed: implementing an interface (implements).

Kinds of Classes and Design

Kinds of Classes

A class is a template that defines an object's structure and behavior. By purpose, there are several kinds:

KindPropertyExample
Enumeration (enum)Has a fixed set of objectsenum Day { MONDAY, TUESDAY, ... }
SingletonOnly one object can be createdprivate constructor + static single object
AbstractCannot be instantiatedabstract class Shape
Sealed (Java 17+)Subclasses form a fixed setsealed interface Move permits Walk, Run
FinalCannot be subclassedfinal class String
Data (record)Its objects are immutablerecord Point(double x, double y)
UtilityContains only static methodsMath, Arrays
Applicationmain method includedThe class where the program starts

Kinds of Classes and Design

Kinds of Classes: Example

final class Utils {             // utility, final class
  private Utils() { }         // no instances
  static int square(int x) { return x * x; }
}
class Settings {                   // singleton
  private static final Settings INSTANCE = new Settings();
  private Settings() { }
  static Settings get() { return INSTANCE; }
}
abstract class Shape {            // abstract class
  abstract double area();
}
// sealed (Java 17+)
sealed interface Move permits Walk, Run { }
final class Walk implements Move { }
final class Run implements Move { }
public class Kinds {           // application class
  public static void main(String[] args) {
    System.out.println(Utils.square(7));
    System.out.println(Settings.get() == Settings.get());
  }
}
Output
49
true
  • Utils: private constructor blocks instances, leaving only static methods; final blocks subclassing.
  • Settings: the single object is the same every time, so == gives true.
  • new Shape() is a compile error (abstract); Move can be implemented only by Walk and Run.

Kinds of Classes and Design

Design Example: Rational

public class Rational {
  // Representation: hidden fields
  private int num, den;
  // Interface: public constructor and methods
  public Rational(int num, int den) {
    int g = gcd(Math.abs(num), Math.abs(den));
    this.num = num / g;
    this.den = den / g;
  }
  public Rational add(Rational d) {
    int newNum = num * d.den + d.num * den;
    return new Rational(newNum, den * d.den);
  }
  @Override
  public String toString() { return num + "/" + den; }
  // Implementation detail: hidden helper
  private static int gcd(int a, int b) {
    while (b != 0) { int k = a % b; a = b; b = k; }
    return a;
  }
}
  • Interface: public constructor, add, toString.
  • Representation: private int num, den; the constructor reduces the fraction.
  • Implementation: method bodies and the hidden gcd helper (Euclid's algorithm).
  • add does not change the current object; it returns a new object.

a = new Rational(8, 10), b = new Rational(2, 3); println(a) and println(a.add(b)):

Output
4/5
22/15

Kinds of Classes and Design · Step-by-step code trace

Rational: Code Trace

StackHeapRational()num6den8g?main()a?Rational #1num0den0

new Rational(6, 8): the object's fields start at 0; the constructor's parameters are 6 and 8.

StackHeapgcd()a6b8k-Rational()num6den8g?main()a?Rational #1num0den0

The hidden helper gcd(6, 8) is called (Euclid's algorithm). Users cannot see this method.

StackHeapgcd()a8b6k6Rational()num6den8g?main()a?Rational #1num0den0

6 % 8 = 6; a ← 8, b ← 6. In the first round the numbers swap.

StackHeapgcd()a6b2k2Rational()num6den8g?main()a?Rational #1num0den0

8 % 6 = 2; a ← 6, b ← 2.

StackHeapgcd()a2b0k0Rational()num6den8g?main()a?Rational #1num0den0

6 % 2 = 0; a ← 2, b ← 0. b == 0: the loop ends.

StackHeapRational()num6den8g2main()a?Rational #1num3den46/8 → 6/2 = 3, 8/2 = 4

gcd returns 2; the constructor stores the reduced fraction: the object is 3/4. The representation always stays reduced.

StackHeapmain()abRational #1num3den4Rational #2num1den6gcd(1, 6) = 1 → 1/6

Same steps for (1, 6): gcd returns 1; the fraction is already reduced: 1/6.

StackHeapadd()thisdnewNum22main()abRational #1num3den4Rational #2num1den63·6 + 1·4 = 22

a.add(b): this = #1, d = #2. Since this is the same class, private fields such as d.den can be read.

StackHeapRational()num22den24g2add()thisdnewNum22main()abRational #1num3den4Rational #2num1den6Rational #3num11den12gcd(22, 24) = 2 → 11/12

new Rational(22, 24): gcd finds 2 via 24, 22, 2, 0; the new object is 11/12.

StackHeapmain()abRational #1num3den4Rational #2num1den6Rational #3num11den12add() returned a new object; a is still 3/4

First the result (#3), then a is printed: add does not change the current object; it returns a new one.

public Rational(int num, int den) {
    int g = gcd(Math.abs(num), Math.abs(den));
    this.num = num / g;
    this.den = den / g;
}
private static int gcd(int a, int b) {
    while (b != 0) { int k = a % b; a = b; b = k; }
    return a;
}
public Rational add(Rational d) {
    int newNum = num * d.den + d.num * den;
    return new Rational(newNum, den * d.den);
}
Rational a = new Rational(6, 8);   // main
Rational b = new Rational(1, 6);
System.out.println(a.add(b) + " " + a);

Summary

Summary

ConceptEssence
Class / objectA class is a blueprint; an object is an instance created with new.
ConstructorSame name as the class, no return type; if none is written, a default one is added.
Instance / static memberAn instance field is separate in each object; a static field is single and shared in the class.
Initializersstatic { } once; { } per object, before the constructor body.
Access and hidingFields private; controlled access via get/set.
ReferenceA variable holds a reference, not the object; assignment copies the reference.
this / this(...)The object the method was called on (none in static methods) / another constructor of the same class, on the first line.
== / equalsSame object? / same content?
Wrapperint ↔ Integer: autoboxing and unboxing.
record / enumImmutable data class / fixed set of values.
Inner classesstatic, member, local, anonymous.

Summary

Common Mistakes (1)

Calling an instance method from main without an objecterror: non-static method greet() cannot be referenced from a static context Call it through an object (new Greeter().greet()); if the method really does not depend on an object, make it static.
Writing void on a constructorerror: constructor Bug1 in class Bug1 cannot be applied to given types; public void Bug1(String m) is not a constructor but an ordinary method. Constructors have no return type.
new Product() when only a parameterized constructor existserror: constructor Product in class Product cannot be applied to given types; Once you write a constructor, no default one is added; write a no-arg constructor too if you need one.
Forgetting newerror: cannot find symbol symbol: method Product(String)To create an object, write new Product("Pen").

Summary

Common Mistakes (2)

Accessing a private field from outsideerror: balance has private access in BankAccount Access the field through the class's get/set methods.
this in a static methoderror: non-static variable this cannot be referenced from a static context A static method has no object.
Forgetting this (shadowing)name = name; // compiles, field stays nullThe parameter shadows the field; the right form is this.name = name;.
this(...) not on the first lineerror: call to this must be first statement in constructor Delegating to another constructor must be the constructor's first statement.

Summary

Common Mistakes (3)

Comparing objects with ==k1 == k2 // falseCompare contents with equals(), including String and wrappers.
Using a null referenceNullPointerExceptionYou cannot call a method before the object is created or after null is assigned; check for null first.
Trying to change a record fielderror: x has private access in Point Records are immutable; for a new value, create a new object.
Creating a member inner class in static mainerror: non-static variable this cannot be referenced from a static context The right way: outer.new MemberInner(); or make the inner class static.

Summary

Worked Problems (1)

Problem 1. What does it print?

class Counter {
  static int total = 0;
  int count = 0;
  void inc() { total++; count++; }
}
public class Problem1 {
  public static void main(String[] args) {
    Counter a = new Counter(), b = new Counter();
    a.inc(); a.inc(); b.inc();
    System.out.print(a.count + " " + b.count);
    System.out.println(" " + Counter.total);
  }
}

Problem 2. What does it print?

class Box { int value; }
public class Problem2 {
  public static void main(String[] args) {
    Box k1 = new Box();
    k1.value = 5;
    Box k2 = k1;
    k2.value = 9;
    Box k3 = new Box();
    k3.value = 9;
    System.out.println(k1.value);
    System.out.println(k1 == k2);
    System.out.println(k2 == k3);
  }
}
Show answers
  1. 2 1 3. count is separate in each object (a: 2, b: 1); total is static, so it counts all three calls: 3.
  2. 9, true, false. k2 = k1 makes both point to the same object: after k2.value = 9, k1.value is 9 too. k3 is a separate object; even with equal values, == gives false.

Summary

Worked Problems (2)

Problem 3. What does it print?

class A {
  static { System.out.print("S"); }
  { System.out.print("I"); }
  A() { System.out.print("C"); }
}
public class Problem3 {
  public static void main(String[] args) {
    System.out.print("M");
    new A();
    new A();
    System.out.println();
  }
}

Problem 4. What does it print?

class Box { int value; }
public class Problem4 {
  static void change(Box k) {
    k.value = 100;
    k = new Box();
    k.value = 7;
  }
  public static void main(String[] args) {
    Box x = new Box();
    x.value = 1;
    change(x);
    System.out.println(x.value);
  }
}
Show answers
  1. MSICIC. First, main prints "M". Class A is loaded at the first new A(): the static block runs once (S); then, for each object, the instance initializer (I) and the constructor (C).
  2. 100. change gets a copy of the reference: k.value = 100 changes the original object; k = new Box() only redirects the local copy to another object; x is unaffected.

Summary

Worked Problems (3)

Problem 5. What does it print?

record Money(int lira) { }
public class Problem5 {
  public static void main(String[] args) {
    Money p1 = new Money(10);
    Money p2 = new Money(10);
    Integer i1 = 1000, i2 = 1000;
    System.out.println(p1.equals(p2));
    System.out.println(p1 == p2);
    System.out.println(i1.equals(i2));
    System.out.println(p1);
  }
}

Problem 6. What does it print?

class Point {
  int x, y;
  Point(int x, int y) {
    this.x = x;
    this.y = y;
  }
}
public class Problem6 {
  public static void main(String[] args) {
    Point a = new Point(1, 2);
    Point b = new Point(1, 2);
    System.out.println(a.equals(b));
    System.out.println(a.x == b.x);
  }
}
Show answers
  1. true / false / true / Money[lira=10]. A record's equals compares contents and == compares references; for Integer, equals is always safe.
  2. false / true. equals is not overridden: Object's version compares references. a.x == b.x compares two int values.

Summary

Exercises

  1. Book class: private title, author, pageCount; a three-parameter constructor, getters and toString().
  2. Book: add a static bookCount counter and a setPageCount that accepts only positive values.
  3. Circle class: radius, area(), perimeter(). new Circle(3): print both to two decimal places.
  4. Season enum: print its values with their ordinals.
  5. StudentRecord(String name, int id) record: write it and print an instance.
Answers / hints
  1. this.title = title; ...; toString() → Nutuk (Atatürk, 600 p.)
  2. In the constructor, bookCount++;, in the setter if (pageCount > 0) ...; for a second book with −5 pages, pages stay 0 and the counter is 2: 0 2
  3. Math.PI * radius * radius, 2 * Math.PI * radius; printf("%.2f %.2f%n", ...) → 28,27 18,85 (comma decimals under a Turkish locale).
  4. for (Season s : Season.values()) → 0:SPRING 1:SUMMER 2:FALL 3:WINTER
  5. record StudentRecord(String name, int id) { } → StudentRecord[name=Ali, id=7]

Summary

References

  • Oracle, The Java Tutorials: "Classes and Objects", "Nested Classes", "Enum Types", "Record Classes", "Autoboxing and Unboxing".
  • J. Gosling et al., The Java Language Specification, Java SE 21 Edition (Chapter 8 Classes: 8.3 Fields, 8.6–8.7 Initializers, 8.8 Constructors, 8.9 Enum, 8.10 Record).
  • P. Deitel and H. Deitel, Java: How to Program, Early Objects, 11th ed., Pearson, 2017 (Chapters 3 and 8: Classes and Objects).
  • K. Sierra and B. Bates, Head First Java, 3rd ed., O'Reilly, 2022.
  • C. S. Horstmann, Core Java, Volume I: Fundamentals, 12th ed., 2022 (Chapter 4: Objects and Classes).
  • A. B. Downey and C. Mayfield, Think Java, 2nd ed., O'Reilly, 2019 (Chapters 10–11).
  • J. Bloch, Effective Java, 3rd ed., Addison-Wesley, 2018 (items on equals, hashCode, toString).

The End

Chapter 4.1: Objects and Classes
Previous: Chapter 3.5: Recursion · Next: Chapter 4.2: Encapsulation
1 / 1 Sercan KÜLCÜ. All rights reserved.