【发布时间】:2021-10-17 16:01:22
【问题描述】:
我最近了解到调用包含构造函数的类意味着它只会调用构造函数,但是如果我想从 Main 中的该类调用方法呢?
假设我有一个看起来像这样的类
public class Student {
private String lastname, firstname, course;
private int[] grades;
static int total;
public Student(String lastname, String firstname, String course, int[] grades) {
this.lastname = lastname;
this.firstname = firstname;
this.course = course;
this.grades = grades;
}
public boolean hasFailingGrade() {
//statements
}
return failed;
}
public void showDetails() {
//statements
}
}
在Main 中,我想创建Student 的实例并调用showDetails(),但是,该实例仅引用构造函数。如何从Student 调用方法?我四处搜索,但只找到有关如何调用构造函数的文章。
这是我的Main 班级的样子
import java.util.Scanner;
import java.util.ArrayList;
import java.io.*;
public class MainApp {
public static void main(String args[]) throws FileNotFoundException {
String firstname, lastname, course;
int[] grades = new int[5];
ArrayList<Student> list = new ArrayList<Student>();
Scanner in = new Scanner(new File("person.txt"));
Scanner in2 = new Scanner(new File("person.txt"));
while(in.hasNext()) {
lastname = in.nextLine();
firstname = in.nextLine();
course = in.nextLine();
for (int i = 0; i < 4; i++)
grades[i] = in2.nextInt();
list.add(new Student(lastname, firstname, course, grades));
}
Student studentClass = new Student();
Student.showDetails();
}
}
【问题讨论】:
-
“实例仅引用构造函数”到底是什么意思?一旦你引用了一个类的实例,你就可以使用该引用调用该类的成员函数。
标签: java class constructor