java - 如何在java中返回匿名实例化对象

标签 java object return anonymous

在第 4 步,我必须使用 4 个输入的信息项返回一个匿名实例化的 Student 对象。由于我找不到任何解决此问题的论坛,因此我需要一些设置帮助或示例。

import java.util.Scanner;

public class Students
{
  private static Scanner input = new Scanner(System.in);

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

    students = getStudents();
    printStudents(students);
  }

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

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

  private static Student getStudent()
  {
    String name,
           address,
           major;
    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();
    purgeInputBuffer();

    return ___________________________________________________;     // Step 4
  }

  private static void printStudents(Student[] s)
  {
    System.out.println();
    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
    // ----------------------------------------------------
    input.nextLine();
  }
}

最佳答案

简单

return new Student(constructor args);

其中构造函数参数是您的Student构造函数所需的任何参数。

这里使用的“匿名”不是标准的 Java 术语。我想,由于您没有将对象引用分配给局部变量,因此可以将其视为“匿名”。由于 getStudent() 是在 getStudents() at

中调用的,因此它不会长期保持匿名状态。
temp[i] = getStudent();

因此引用将立即保存(到数组中)。

“匿名”出现在术语“匿名子类”中,但这是一个完全不同的概念,您可能还没有接触过。

关于java - 如何在java中返回匿名实例化对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36440248/

相关文章:

java - 新的 BigInteger(String) 性能/复杂性

java - 如何在 SWT/Java 中将数据附加到 TreeItem?

c++ - 递归返回和基本流程

c - 如何使用函数中生成的两个随机数作为矩阵坐标?

c# - 如何在另一个对象中存储对对象属性的引用?

c++ - 在 int 返回函数中返回 "false"

java - 在 Java 中更改 SOAP 接口(interface)和弃用 Web 方法

java - Int 到 BigInteger,有什么区别?

java - 创建带有填充变量且没有任何 setter 或构造函数的对象

java - 保存单例对象