EZ

Eduzan

Learning Hub

Eduzan
Eduzan / Java

Classes in Java

Object-Oriented Programming (OOP) refers to the concept of structuring software as a collection of objects that include both data and behavior. In this approach, programs revolve around objects, which helps simplify software development and maintenance. Instead of focusing solely on actions or logic, OOP allows for more flexible and maintainable software. It makes understanding and working with the program easier by bringing data and methods into a single location: the object.

Key Concepts of OOP:

  • Object
  • Class
  • Encapsulation
  • Inheritance
  • Polymorphism
  • Abstraction

Importance of Classes and Objects in OOP

Classes:

A class acts as a blueprint or prototype from which objects are created. It defines a set of attributes and behaviors that are common to all objects of that type. The primary reasons classes are essential in OOP are:

  • They offer a structure for creating objects that bind data and methods together.
  • They contain method and variable definitions.
  • They support inheritance, allowing for the maintenance of a class hierarchy.
  • They enable the management of access to member variables.

Objects:

An object is the core unit of OOP. It represents real-life entities and combines attributes and behaviors.

Objects consist of:

  • State: Represented by the object’s attributes.
  • Behavior: Represented by the object’s methods.
  • Identity: A unique identifier for each object, allowing it to interact with other objects.

In OOP, objects are important because they can call non-static functions not present in the main method but existing within the class.

Example of Creating and Using Objects and Classes:

To better understand this, let’s take an example where we add two numbers. By creating separate objects for each number, we can perform the necessary operations. Here’s a demonstration of the use of objects and classes:

// Java program to demonstrate objects and classes

public class Animal {
    // Instance variables
    String name;
    String species;
    int age;

    // Constructor for the Animal class
    public Animal(String name, String species, int age) {
        this.name = name;
        this.species = species;
        this.age = age;
    }

    // Method to return the animal's name
    public String getName() {
        return name;
    }

    // Method to return the animal's species
    public String getSpecies() {
        return species;
    }

    // Method to return the animal's age
    public int getAge() {
        return age;
    }

    // Method to print the animal's details
    @Override
    public String toString() {
        return "This is a " + species + " named " + name + " and it is " + age + " years old.";
    }

    public static void main(String[] args) {
        // Creating an object of the Animal class
        Animal animal1 = new Animal("Buddy", "Dog", 3);
        System.out.println(animal1.toString());
    }
}

Output:

This is a Dog named Buddy and it is 3 years old.

Object Creation Techniques in Java:

1. Using the new Keyword:

This is the simplest and most common way to create an object in Java.

// Java program to demonstrate object creation using the new keyword

class Vehicle {
    String type;
    String model;

    Vehicle(String type, String model) {
        this.type = type;
        this.model = model;
    }
}

public class Test {
    public static void main(String[] args) {
        // Creating two objects of the Vehicle class
        Vehicle car = new Vehicle("Car", "Sedan");
        Vehicle bike = new Vehicle("Bike", "Cruiser");

        // Accessing object data
        System.out.println(car.type + ": " + car.model);
        System.out.println(bike.type + ": " + bike.model);
    }
}

Output:

Car: Sedan
Bike: Cruiser

2. Using Class.newInstance():

This method dynamically creates objects, invoking a no-argument constructor.

// Java program to demonstrate object creation using Class.newInstance()

class Example {
    void displayMessage() {
        System.out.println("Welcome to OOP!");
    }
}

public class Test {
    public static void main(String args[]) {
        try {
            Class<?> cls = Class.forName("Example");
            Example obj = (Example) cls.newInstance();
            obj.displayMessage();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

Output:

Welcome to OOP!

3. Using the clone() Method:

This method creates a copy (or clone) of an existing object. The class must implement the Cloneable interface.

// Java program to demonstrate object creation using the clone() method

class Person implements Cloneable {
    int id;
    String name;

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

    // Cloning method
    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

public class Test {
    public static void main(String[] args) {
        try {
            // Creating original object
            Person person1 = new Person(101, "John");

            // Cloning person1
            Person person2 = (Person) person1.clone();

            System.out.println(person1.id + ", " + person1.name);
            System.out.println(person2.id + ", " + person2.name);
        } catch (CloneNotSupportedException e) {
            System.out.println(e);
        }
    }
}

Output:

101, John
101, John
End of lesson.