In this program, we will create a Sample class with a method. Then we will create an array of objects.
Program/Source Code:
The source code to create an array of objects is given below. The given program is compiled and executed successfully.
// Java program to create an array
// of objects
class Sample {
void sayHello() {
System.out.println("Hello World");
}
}
class Main {
public static void main(String args[]) {
Sample[] arrObj = new Sample[3];
arrObj[0] = new Sample();
arrObj[1] = new Sample();
arrObj[2] = new Sample();
arrObj[0].sayHello();
arrObj[1].sayHello();
arrObj[2].sayHello();
}
}
Output:
Hello World
Hello World
Hello World
Explanation:
In the above program, we created a Sample class and public class Main. The Sample class contains a method sayHello(). The sayHello() method prints the "Hello World" message.
The Main class contains a static method main(). The main() is an entry point for the program. Here, we created an array of 3 objects. Then we called the sayHello() method of each object and printed the "Hello World" message.
In this program, we will create a Sample class with a method. Then we will create an array of objects.
Program/Source Code:
The source code to create an array of objects is given below. The given program is compiled and executed successfully.
Output:
Explanation:
In the above program, we created a Sample class and public class Main. The Sample class contains a method sayHello(). The sayHello() method prints the "Hello World" message.
The Main class contains a static method main(). The main() is an entry point for the program. Here, we created an array of 3 objects. Then we called the sayHello() method of each object and printed the "Hello World" message.