Classes and Objects

Learn how to define classes, create objects, and access their properties and methods. Implement your own custom data types.


Java Classes and Objects

What are Classes and Objects?

In object-oriented programming (OOP), a class is a blueprint or template for creating objects. It defines the properties (data) and behaviors (methods) that objects of that class will have.

An object is an instance of a class. It's a concrete realization of the class's blueprint. Think of a class as the design for a house, and an object as the actual house built from that design. Multiple houses (objects) can be built from the same design (class).

Defining Classes in Java

To define a class in Java, use the class keyword, followed by the class name. Inside the class, you define the data members (fields/attributes) and methods.

 class Dog {
    // Instance variables (data members)
    String breed;
    String name;
    int age;

    // Constructor (used to create objects)
    public Dog(String breed, String name, int age) {
        this.breed = breed;
        this.name = name;
        this.age = age;
    }

    // Method (behavior)
    void bark() {
        System.out.println("Woof!");
    }

    // Method to get the dog's name
    String getName() {
        return name;
    }
} 

Explanation:

  • class Dog: Defines a class named "Dog".
  • String breed;, String name;, int age;: These are instance variables, also known as attributes or fields. Each `Dog` object will have its own copy of these variables.
  • public Dog(String breed, String name, int age) { ... }: This is a constructor. It's a special method that is called when you create a new object of the class. It initializes the object's state. The `this` keyword refers to the current object.
  • void bark() { ... }: This is a method. It defines a behavior that `Dog` objects can perform.
  • String getName() { ... }: Another method that returns the `name` of the dog.

Creating Objects in Java

To create an object of a class, use the new keyword followed by the class name and parentheses (which may contain arguments for the constructor).

 public class Main {
    public static void main(String[] args) {
        // Create two Dog objects
        Dog myDog = new Dog("Golden Retriever", "Buddy", 3);
        Dog anotherDog = new Dog("Labrador", "Lucy", 5);

        // Access object properties and call methods
        System.out.println("My dog's name is: " + myDog.getName()); // Output: My dog's name is: Buddy
        myDog.bark(); // Output: Woof!

        System.out.println("Another dog's breed is: " + anotherDog.breed); // Output: Another dog's breed is: Labrador
    }
} 

Explanation:

  • Dog myDog = new Dog("Golden Retriever", "Buddy", 3);: This line creates a new `Dog` object using the constructor. The `new` keyword allocates memory for the object. `myDog` is a reference variable that holds the memory address of the newly created `Dog` object.
  • myDog.getName(): This calls the `getName()` method on the `myDog` object. The dot (`.`) operator is used to access members (properties and methods) of an object.
  • anotherDog.breed: This directly accesses the `breed` instance variable of the `anotherDog` object.

Accessing Properties and Methods

You access the properties and methods of an object using the dot operator (.). For example:

  • objectName.propertyName to access a property.
  • objectName.methodName() to call a method.

The visibility of properties and methods (public, private, protected) determines whether they can be accessed from outside the class. Best practice generally favors using `private` instance variables and providing `public` getter and setter methods (accessors and mutators) to control access to the data, promoting encapsulation.

Implementing Your Own Custom Data Types

Classes allow you to define your own custom data types. This is a powerful feature of OOP. You can create classes that represent anything you need in your application.

For example, you can create a Point class to represent a point in 2D space:

 class Point {
    int x;
    int y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    // Method to calculate the distance from this point to another point
    double distance(Point otherPoint) {
        int dx = this.x - otherPoint.x;
        int dy = this.y - otherPoint.y;
        return Math.sqrt(dx * dx + dy * dy);
    }
}

public class Main {
    public static void main(String[] args) {
        Point p1 = new Point(1, 2);
        Point p2 = new Point(4, 6);

        double distance = p1.distance(p2);
        System.out.println("Distance between p1 and p2: " + distance); // Output: Distance between p1 and p2: 5.0
    }
} 

In this example, the Point class encapsulates the x and y coordinates of a point. It also has a method to calculate the distance between two points. This demonstrates how you can create custom data types with their own data and behavior using classes in Java.