Skip to content
Advertisement

How to call a method from a class that contains a constructor?

I recently learned that calling a class that contains a constructor means that it will call the constructor only, but what if I want to call a method from that class in Main?

Let’s say I have a class that looks like this

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
    }
}

And in Main, I want to create an instance of Student and call showDetails(), however, the instance references the constructor only. How do I call the method from Student? I searched around but I only found articles regarding how to call a constructor.

Here’s how my Main class looks like

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();

    }
}

Advertisement

Answer

I think you have a slight misunderstanding of what instantiating an object means. When you make a call to new Student(), you are instantiating a new instance of your Student class. This instantiation process involves an initial call to the constructor. Think of the constructor method as a function that sets up everything you need for your class to work as you expect.

However, once you instantiate and instance of Student, you then have access to all public methods and fields available from that instance. In your example, your Student class has a public method called showDetails().

So you could write something like this in main:

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

By creating an instance of the class, you gain access to all public methods on the class.

Hope this clears up your confusion!

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement