Module: Object-Oriented Programming Basics

Classes and Objects

Java Core: Object-Oriented Programming Basics - Classes and Objects

This document covers the fundamental concepts of Classes and Objects in Java, the cornerstone of Object-Oriented Programming (OOP).

1. What is Object-Oriented Programming (OOP)?

OOP is a programming paradigm based on the concept of "objects", which contain data (fields/attributes) and code (methods/behaviors) to manipulate that data. It aims to model real-world entities and their interactions. Key principles of OOP include:

  • Encapsulation: Bundling data and methods that operate on that data within a single unit (the object).
  • Abstraction: Hiding complex implementation details and exposing only essential features to the user.
  • Inheritance: Creating new classes (child/subclasses) based on existing classes (parent/superclasses), inheriting their properties and behaviors.
  • Polymorphism: The ability of an object to take on many forms.

2. Classes: The Blueprint

A class is a blueprint or template for creating objects. It defines the characteristics (data) and behaviors (methods) that objects of that class will possess. Think of it like a cookie cutter – the cutter defines the shape, but you need to use the cutter to create actual cookies.

Syntax:

class ClassName {
  // Fields (Attributes) - Data
  // Methods (Behaviors) - Actions
}

Example: Dog Class

class Dog {
  // Fields (Attributes)
  String breed;
  String name;
  int age;
  String color;

  // Methods (Behaviors)
  void bark() {
    System.out.println("Woof!");
  }

  void eat() {
    System.out.println(name + " is eating.");
  }

  void sleep() {
    System.out.println(name + " is sleeping.");
  }
}
  • class Dog: Declares a class named Dog.
  • String breed;, String name;, int age;, String color;: These are fields or attributes that describe a dog. They hold data.
  • void bark(), void eat(), void sleep(): These are methods that define what a dog can do. They contain code.
  • void indicates that these methods don't return any value.

3. Objects: Instances of a Class

An object is an instance of a class. It's a concrete realization of the blueprint defined by the class. Using the cookie cutter analogy, the object is the actual cookie created from the cutter.

Creating Objects (Instantiation):

Objects are created using the new keyword.

Syntax:

ClassName objectName = new ClassName();

Example: Creating Dog Objects

public class Main {
  public static void main(String[] args) {
    // Create a Dog object named myDog
    Dog myDog = new Dog();

    // Set the attributes of myDog
    myDog.breed = "Golden Retriever";
    myDog.name = "Buddy";
    myDog.age = 3;
    myDog.color = "Golden";

    // Create another Dog object named yourDog
    Dog yourDog = new Dog();
    yourDog.breed = "Poodle";
    yourDog.name = "Coco";
    yourDog.age = 5;
    yourDog.color = "White";

    // Call methods on the objects
    myDog.bark();  // Output: Woof!
    yourDog.eat(); // Output: Coco is eating.
  }
}
  • Dog myDog = new Dog();: Creates a new Dog object and assigns it to the variable myDog.
  • myDog.breed = "Golden Retriever";: Sets the breed attribute of the myDog object to "Golden Retriever". We access attributes using the dot (.) operator.
  • myDog.bark();: Calls the bark() method on the myDog object. Again, we use the dot operator.

4. Access Modifiers

Access modifiers control the visibility of class members (fields and methods).

  • public: Accessible from anywhere.
  • private: Accessible only within the same class. This is a key part of encapsulation.
  • protected: Accessible within the same package and by subclasses (even in different packages).
  • (default/package-private): Accessible within the same package. No keyword is used.

Example:

class Car {
  public String model;  // Accessible from anywhere
  private int year;     // Accessible only within the Car class
  protected String engineType; // Accessible within the same package and by subclasses

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

  public int getYear() { // Getter method to access the private year field
    return year;
  }
}

In this example, year is private, so it can't be directly accessed from outside the Car class. We provide a getter method (getYear()) to allow controlled access to its value. This is a common practice in OOP.

5. Constructors

A constructor is a special method that is called when an object of a class is created. It's used to initialize the object's fields.

Characteristics of Constructors:

  • Has the same name as the class.
  • Has no return type (not even void).
  • Can have parameters.
  • If no constructor is explicitly defined, Java provides a default constructor (with no parameters).

Example:

class Rectangle {
  int width;
  int height;

  // Constructor with parameters
  public Rectangle(int width, int height) {
    this.width = width;
    this.height = height;
  }

  // Default constructor (no parameters)
  public Rectangle() {
    width = 1;
    height = 1;
  }

  public int calculateArea() {
    return width * height;
  }
}
  • public Rectangle(int width, int height): A constructor that takes width and height as parameters and initializes the object's fields.
  • public Rectangle(): A default constructor that sets width and height to 1.

6. this Keyword

The this keyword refers to the current object. It's used to:

  • Distinguish between instance variables and local variables with the same name.
  • Call another constructor within the same class.
  • Return the current object from a method.

Example (from the Rectangle class):

public Rectangle(int width, int height) {
  this.width = width;  // 'this.width' refers to the instance variable
  this.height = height; // 'width' and 'height' refer to the parameters
}

Summary

Classes and objects are the fundamental building blocks of Java OOP. Understanding these concepts is crucial for writing well-structured, maintainable, and reusable code. This document provides a basic introduction; further exploration of OOP principles like inheritance and polymorphism will enhance your understanding and ability to create complex applications.