如何从包含构造函数的类调用方法?



我最近了解到调用包含构造函数的类意味着它将只调用构造函数,但是如果我想在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();
}
}

我认为您对实例化对象的含义有一点误解。当您调用new Student()时,您正在实例化Student类的新实例。这个实例化过程包括对构造函数的初始调用。可以把构造函数方法看作是一个函数,它设置了使类按预期工作所需的一切。

但是,一旦实例化了Student的实例,就可以访问该实例中可用的所有公共方法和字段。在您的示例中,您的Student类有一个名为showDetails()的公共方法。

你可以在main中这样写:

Student student = new Student("Smith", "John", "English", [95, 88, 73]);
student.showDetails();

通过创建类的实例,您可以访问该类的所有公共方法。

希望这能澄清你的困惑!

最新更新