Java Fundamentals  «Prev  Next»
Lesson 2 Creating objects from classes
ObjectiveCreate objects from classes.

Creating Objects from Classes in Java

Programmers new to Java are often puzzled by the fact that memory management is handled automatically. Most other programming languages such as C and C++ place the responsibility of memory management in the hands of programmers. Managing memory by hand in C/C++ certainly gives you more flexibility, but it comes at the cost of memory leaks. When memory is allocated and then accidentally forgotten, it is effectively lost to the system, which is a very bad thing.
Java solves the memory leak problem by taking complete charge of memory management. When you create an object from a class using the new operator, the memory for the object is allocated and managed by Java. When you are later finished with the object, Java frees up the memory automatically. The miracle of Java's memory management has to do with a process known as garbage collection. Garbage collection is when Java periodically looks for objects that are no longer being used so that it can free the memory associated with them. Even a programming language as clean as Java has to clean house from time to time.
    Ojbect Creation in Java:
  • When you create an object from a class it is known as an instance of the class. This process of creating an instance of an object is referred to as instantiating an object. The creation of an object always begins with a constructor, which is a special method that is called when an object is first created. Constructors have the same name as the class to which they belong, and are a good place to perform any initialization required of the class. If you do not provide a constructor for your class, Java will provide a default constructor for you. The default constructor has no arguments and does not perform any initialization.
    The primary means of creating objects in Java is the new operator. In the following example, an instance of class Circle is created, the instance variable radius is set to 5.0, and then the instance method area() is invoked to display the area of the circle. Because no constructors were provided in the Circle class, the Java-provided default constructor was used.


Creating an object using the "new" keyword.

Here is an example of creating an object from a class in Java using the "new" keyword: Step-by-Step Example
  1. Define the Class: Create a simple class named `Car` with a constructor and some attributes.
    public class Car {
        // Attributes
        String make;
        String model;
        int year;
    
        // Constructor
        public Car(String make, String model, int year) {
            this.make = make;
            this.model = model;
            this.year = year;
        }
    
        // Method to display car details
        public void displayDetails() {
            System.out.println("Make: " + make);
            System.out.println("Model: " + model);
            System.out.println("Year: " + year);
        }
    }
    
  2. Create an Object: Use the `new` keyword to create an instance (object) of the `Car` class.
    public class Main {
        public static void main(String[] args) {
            // Create an object of the Car class
            Car myCar = new Car("Toyota", "Corolla", 2021);
    
            // Display the details of the car
            myCar.displayDetails();
        }
    }
    

Explanation
  • Class Definition: The `Car` class has three attributes (`make`, `model`, `year`) and a constructor to initialize these attributes. It also has a method `displayDetails` to print out the car's details.
  • Object Creation: In the `Main` class, the `new` keyword is used to create a new instance of the `Car` class. The constructor is called with the arguments `"Toyota"`, `"Corolla"`, and `2021` to initialize the object.
  • Using the Object: The `myCar` object calls the `displayDetails` method to print out its attributes.

Output When the `Main` class is run, the output will be:
Make: Toyota
Model: Corolla
Year: 2021

This demonstrates how to create and use an object from a class in Java using the `new` keyword.


Using Factory Methods in Java to create Objects

In Java, an alternative to using the `new` keyword for creating objects is to use factory methods. Factory methods are static methods that return instances of a class. They can provide more flexibility and control over the object creation process.
Example of Factory Method Here’s how you can implement and use a factory method to create objects:
  1. Define the Class with a Private Constructor and a Factory Method: Modify the `Car` class to include a private constructor and a static factory method.
    public class Car {
        // Attributes
        String make;
        String model;
        int year;
    
        // Private constructor
        private Car(String make, String model, int year) {
            this.make = make;
            this.model = model;
            this.year = year;
        }
    
        // Factory method to create a Car object
        public static Car createCar(String make, String model, int year) {
            return new Car(make, model, year);
        }
    
        // Method to display car details
        public void displayDetails() {
            System.out.println("Make: " + make);
            System.out.println("Model: " + model);
            System.out.println("Year: " + year);
        }
    }
    
  2. Use the Factory Method to Create an Object: In the `Main` class, use the factory method to create an instance of the `Car` class.
    public class Main {
        public static void main(String[] args) {
            // Create an object of the Car class using the factory method
            Car myCar = Car.createCar("Toyota", "Corolla", 2021);
    
            // Display the details of the car
            myCar.displayDetails();
        }
    }
    
Explanation
  • Private Constructor: The `Car` class now has a private constructor, which prevents direct instantiation using the `new` keyword outside the class.
  • Factory Method: The static method `createCar` acts as a factory method, encapsulating the creation logic and returning a new `Car` object.
  • Using the Factory Method: In the `Main` class, the `createCar` factory method is called to create a `Car` object.

Benefits of Factory Methods
  • Encapsulation: Factory methods encapsulate the creation logic, which can be useful if the creation process is complex or involves multiple steps.
  • Flexibility: They allow returning instances of different subclasses based on input parameters.
  • Named Constructors: Factory methods can have descriptive names, making the code more readable (e.g., `Car.createElectricCar()`).

Output
When the `Main` class is run, the output will be:
Make: Toyota
Model: Corolla
Year: 2021

This demonstrates an alternative to the `new` keyword in Java by using factory methods to create objects.


class Circle {
  double radius;
  double area() {
    return Math.PI * radius * radius;
  }
}
class CircleTest {
  public static void main(String[] args) {
    Circle c = new Circle();
    c.radius = 5.0;
    System.out.println(c.area());
  }
}

Instance Variables Methods - Exercise

In this exercise, you will practice using instance variables and methods.
Instance Variables Methods - Exercise

SEMrush Software