How to return an anonymous instantiated object in java

At step 4 i have to return an anonymous instantiated Student object using the 4 entered items of information. Since i could not find any forums addressing this, i need some help setting it up or an example.

import java.util.Scanner;

public class Students
  private static Scanner input = new Scanner(;

  public static void main(String[] args)
    Student[] students;

    students = getStudents();

  private static Student[] getStudents()
    Student[] temp;
    int       how_many;

    System.out.print("How many students? ");
    how_many = input.nextInt();
    temp =  new Student[input.nextInt()];  // Step 1 
    for (int i = 0; i < temp.length; i++)
      temp[i] = getStudent();     // Step 2
    return temp;    // Step 3

  private static Student getStudent()
    String name,
    double gpa;

    System.out.print("Enter name: ");
    name = input.nextLine();
    System.out.print("Enter address: ");
    address = input.nextLine();
    System.out.print("Enter major: ");
    major = input.nextLine();
    System.out.print("Enter GPA: ");
    gpa = input.nextDouble();

    return ___________________________________________________;     // Step 4

  private static void printStudents(Student[] s)
    for (int i = 0; i < s.length; i++)    // Step 5
      System.out.println(______);     // Step 6

  private static void purgeInputBuffer()
    // ----------------------------------------------------
    // Purge input buffer by reading and ignoring remaining
    // characters in input buffer including the newline
    // ----------------------------------------------------



return new Student(constructor args);

where constructor args are whatever arguments your Student constructor requires.

The use of “anonymous” here is not standard Java terminology. I suppose since you don’t assign the object reference to a local variable it could be considered “anonymous”. It won’t remain anonymous for long since getStudent() is being called in getStudents() at

temp[i] = getStudent();

so the reference will be saved immediately (into the array).

“Anonymous” occurs in the term “anonymous subclass” but that is a completely different concept you probably have not touched on yet.

Leave a Reply

Your email address will not be published. Required fields are marked *