Java Classes and Objects


In Java, classes and objects form the foundation of object-oriented programming (OOP). Understanding how to use classes and objects is essential for creating robust and reusable Java applications. In this guide, we will cover the basics of classes and objects, how to define them, and how to interact with them in Java.

Table of Contents

  1. What Are Classes and Objects?
  2. Defining a Class in Java
  3. Creating Objects in Java
  4. Class Members: Fields, Methods, and Constructors
  5. Access Modifiers in Java
  6. Encapsulation: Hiding Data
  7. Example: A Simple Java Class

What Are Classes and Objects?

  • Class: A class in Java is a blueprint or template for creating objects. It defines the properties (fields) and behaviors (methods) that the objects created from the class will have.
  • Object: An object is an instance of a class. It contains real values for the properties defined in the class and can perform the behaviors (methods) defined by the class.

In Java, everything is associated with a class, and all code is written inside classes.


Defining a Class in Java

To define a class in Java, you use the class keyword, followed by the name of the class. By convention, class names start with an uppercase letter.

Syntax:

public class ClassName {
    // Fields (variables)
    // Methods
    // Constructors
}
  • Fields: Variables that hold the state or data of the class.
  • Methods: Functions that define the behaviors of the class.
  • Constructors: Special methods used to initialize objects.

Example: A Simple Class

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

    // Method
    void startEngine() {
        System.out.println("Engine started");
    }
}

In this example, the Car class has three fields: brand, model, and year. It also has a method startEngine() that simulates starting the car's engine.


Creating Objects in Java

Once you have a class defined, you can create objects from that class. Creating an object is called instantiating a class.

Syntax:

ClassName objectName = new ClassName();
  • ClassName: The name of the class.
  • objectName: The name of the object.
  • new: The keyword used to create a new instance of the class.

Example: Creating Objects from the Car Class

public class Main {
    public static void main(String[] args) {
        // Create an object of the Car class
        Car myCar = new Car();

        // Accessing fields of the object
        myCar.brand = "Toyota";
        myCar.model = "Camry";
        myCar.year = 2020;

        // Calling method on the object
        myCar.startEngine();
        
        // Output object details
        System.out.println("Car brand: " + myCar.brand);
        System.out.println("Car model: " + myCar.model);
        System.out.println("Car year: " + myCar.year);
    }
}

Output:

Engine started
Car brand: Toyota
Car model: Camry
Car year: 2020

In this example, we created an object myCar of the Car class and set its fields. We also called the startEngine() method to simulate starting the car's engine.


Class Members: Fields, Methods, and Constructors

1. Fields (Variables)

Fields represent the state or properties of an object. They are declared inside the class but outside the methods.

Example:

String brand;
int speed;

2. Methods

Methods define the behavior of the objects. You can use methods to manipulate the data (fields) or perform actions.

Example:

void accelerate() {
    speed += 10;
    System.out.println("Accelerated to " + speed + " km/h");
}

3. Constructors

Constructors are special methods used to initialize objects when they are created. Constructors have the same name as the class and are not declared with a return type.

Example:

public Car(String brand, String model, int year) {
    this.brand = brand;
    this.model = model;
    this.year = year;
}

This constructor allows us to create Car objects with initial values for the brand, model, and year fields.


Access Modifiers in Java

Access modifiers in Java define the visibility and accessibility of fields, methods, and classes. The most common access modifiers are:

  1. public: Accessible from anywhere.
  2. private: Accessible only within the class.
  3. protected: Accessible within the same package and by subclasses.
  4. default (no modifier): Accessible only within the same package.

Example:

public class Car {
    private String brand;  // Accessible only within the Car class
    public String model;   // Accessible anywhere

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

    public String getBrand() {
        return brand;
    }
}

In this example, the brand field is private, so it cannot be accessed directly outside the class. However, it can be accessed and modified through the setBrand() and getBrand() methods, which are public.


Encapsulation: Hiding Data

Encapsulation is the concept of hiding the internal details of an object and exposing only the necessary parts. This is achieved by using private fields and public getter and setter methods.

Example of Encapsulation:

public class Car {
    private String brand;

    // Getter method for brand
    public String getBrand() {
        return brand;
    }

    // Setter method for brand
    public void setBrand(String brand) {
        this.brand = brand;
    }
}

In this case, the brand field is hidden from outside access, and it can only be modified using the setBrand() method and accessed using the getBrand() method.


Example: A Simple Java Class

Here’s a complete example combining all of the concepts above:

public class Person {
    // Fields (properties)
    private String name;
    private int age;

    // Constructor
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // Method to display information
    public void introduce() {
        System.out.println("Hello, my name is " + name + " and I am " + age + " years old.");
    }

    // Getter methods
    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    // Setter methods
    public void setName(String name) {
        this.name = name;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

To use the Person class:

public class Main {
    public static void main(String[] args) {
        // Create an object of the Person class
        Person person = new Person("Alice", 25);

        // Call the method
        person.introduce();

        // Access and modify fields through getter and setter
        person.setName("Bob");
        person.setAge(30);

        // Call the method again with updated values
        person.introduce();
    }
}

Output:

Hello, my name is Alice and I am 25 years old.
Hello, my name is Bob and I am 30 years old.