Creating an Array of Class Objects

From Java Example Source Code

Jump to: navigation, search

Contents

[edit] Overview - Creating an Array of Class Objects

This is a Java example program.

[edit] Java Source Code

  • Package: example.array
  • File: EmployeeTest.java
  1. package example.array;
  2.  
  3. public class EmployeeTest {
  4.     public static void main(String[] args) {
  5. 	Employee[] staff = new Employee[3];
  6. 	staff[0] = new Employee("Harry Hacker", 3500);
  7. 	staff[1] = new Employee("Carl Cracker", 7500);
  8. 	staff[2] = new Employee("Tony Tester", 3800);
  9.  
  10. 	for (int i = 0; i < 3; i++)
  11. 	    staff[i].print();
  12.     }
  13. }
  14.  
  15. class Employee {
  16.     private String name;
  17.  
  18.     private double salary;
  19.  
  20.     public Employee(String n, double s) {
  21. 	name = n;
  22. 	salary = s;
  23.     }
  24.  
  25.     public void print() {
  26. 	System.out.println(name + " " + salary);
  27.     }
  28. }

[edit] What Result You Can Get

Run the program, you will get:

Harry Hacker 3500.0
Carl Cracker 7500.0
Tony Tester 3800.0

[edit] Required External Libraries and/or Files for this Java Example

Need nothing.


[edit] How to Run this Java Example Program

We recommend running this Java example program with Eclipse.

For assistance in working with Eclipse, please see How to Run Java Program with Eclipse.

It's fairly easy.



[edit] Question & Answer

Any question?

Click edit and post your question or answer here.


Personal tools