allthingsare๐Ÿ…ฟ๏ธ.com Books โฌ…๏ธ Back allthingsare

โ€œStart where you are. Use what you have. Do what you can.โ€
[Arthur Ashe (1943โ€“1993) โ€“ American tennis champion and activist]


Class Basics


9.1.1 What is a Class?

In Java, a class is the blueprint for creating objects.
Itโ€™s a template that describes:

  • What data the object has (fields or attributes)

  • What actions it can perform (methods)

Think of a class as the design for a house โ€” it defines the rooms, walls, and doors, but no physical house exists until you actually build one.
Once you instantiate a class, you get an object, which is the real thing you can use in your program.

A class groups related data and behavior together.
For example, a Car class might have:

  • Fields: color, speed, model

  • Methods: start(), accelerate(), brake()

Using classes makes your code modular, organized, and scalable โ€” which is the foundation of object-oriented programming (OOP).


9.1.2 Why Use Classes?

Why not just write everything in main with variables and methods?

Classes solve three big problems:

  1. Structure: They organize data + behavior together. Instead of tracking carColor, carSpeed, and carStart() separately, you bundle it all inside Car.

  2. Reusability: You can create many objects from the same class โ€” 10 cars, each with different colors or speeds.

  3. Encapsulation: Classes hide internal details and expose only whatโ€™s needed. This keeps your data safe and your code easier to manage.

In big projects, classes become the building blocks for features.
Databases, APIs, UI elements โ€” everything is modeled with classes.


9.1.3 Basic Class Syntax

The simplest class looks like this:

java
public class Car { String color; int speed; void start() { System.out.println("Car started!"); } void accelerate() { speed += 10; System.out.println("Accelerating. Speed: " + speed); } }

Key parts:

  • public class Car declares the class.

  • String color and int speed are fields.

  • start() and accelerate() are methods that belong to the class.

At this point, this class is just a blueprint โ€” no car exists until you create one.
You do that by instantiating the class, which weโ€™ll cover next.