Q:

Java program to create an array of objects

belongs to collection: Java Class and Object Programs

0

Java program to create an array of objects

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java Class and Object Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to implement default or no-argument c... >>
<< Java program to pass an object as an argument...