0% completed
Creating the Object of the Class
On This Page
How to Create an Object?
Examples
Example 1: Creating an Object and Calling a Method Without Parameters
Example 2: Creating an Object and Calling a Method With Parameters
Example 3: Working with the Animal 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
newkeyword creates the object, andClassName()calls the constructor to initialize it.
We need an object of the class to access its instance 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.
Explanation:
Car myCar = new Car();creates an object of theCarclass.myCar.startEngine();calls thestartEnginemethod, 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.
Explanation:
myCar.setSpeed(80);calls thesetSpeedmethod with the value80as the argument.- 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.
Explanation:
myAnimal.makeSound();calls the method without parameters and prints "Animal is making a sound."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.
Reading Progress
0%
On This Page
How to Create an Object?
Examples
Example 1: Creating an Object and Calling a Method Without Parameters
Example 2: Creating an Object and Calling a Method With Parameters
Example 3: Working with the Animal Class