Java Intermediate

0% completed

Previous
Next
Creating the Object of the Class

In Java, creating an object means instantiating a class. An object is an instance of a class that allows you to access its attributes and methods. To use the behaviors (methods) defined in a class, you must first create an object of that class.

In this lesson, we will learn how to create objects and call methods (with and without parameters) on those objects.

How to Create an Object?

To create an object of a class, we use the new keyword, followed by the class constructor. The general syntax for creating an object is:

ClassName objectName = new ClassName();

Explanation:

  • ClassName: The name of the class you are creating an object from.
  • objectName: The name you assign to the object. This is your reference to access the object.
  • new ClassName(): The new keyword creates the object, and ClassName() calls the constructor to initialize it.

We need to use the object of the class to access the class variables and methods.

Examples

Example 1: Creating an Object and Calling a Method Without Parameters

Let’s use the Car class and call the startEngine method.

Java
Java

. . . .

Explanation:

  1. Car myCar = new Car(); creates an object of the Car class.
  2. myCar.startEngine(); calls the startEngine method, which prints "Engine started."

Example 2: Creating an Object and Calling a Method With Parameters

Now, let’s call the setSpeed method from the Car class, which takes a parameter.

Java
Java

. . . .

Explanation:

  1. myCar.setSpeed(80); calls the setSpeed method with the value 80 as the argument.
  2. The method prints "Car is running at 80 km/h."

Example 3: Working with the Animal Class

Let’s now work with the Animal class and call both methods with and without parameters.

Java
Java

. . . .

Explanation:

  1. myAnimal.makeSound(); calls the method without parameters and prints "Animal is making a sound."
  2. myAnimal.eat("grass"); calls the method with the argument "grass" and prints "Animal is eating grass."

To use a class in Java, you must create an object using the new keyword. Objects allow you to call the class’s methods and access its attributes. In this lesson, we created objects of the Car and Animal classes and called methods with and without parameters.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next