0% completed
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.
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:
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.
Let’s use the Car class and call the startEngine method.
Explanation:
Car myCar = new Car(); creates an object of the Car class.myCar.startEngine(); calls the startEngine method, which prints "Engine started."Now, let’s call the setSpeed method from the Car class, which takes a parameter.
Explanation:
myCar.setSpeed(80); calls the setSpeed method with the value 80 as the argument.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.
.....
.....
.....