Alex
Alex

Reputation: 730

homework: how to invoke a java method

I have:

/*
 * File: NameSurferEntry.java
 * --------------------------
 * This class represents a single entry in the database.  Each
 * NameSurferEntry contains a name and a list giving the popularity
 * of that name for each decade stretching back to 1900.
 */

import acm.util.*;
import java.util.*;

public class NameSurferEntry implements NameSurferConstants {

/* Constructor: NameSurferEntry(line) */
/**
 * Creates a new NameSurferEntry from a data line as it appears
 * in the data file.  Each line begins with the name, which is
 * followed by integers giving the rank of that name for each
 * decade.
 */
    public NameSurferEntry(String line) {
        findName(line);
        findDecades(line);
    }
...

as a class.

How would I call the method NameSurferEntry from within another class.

Upvotes: 0

Views: 427

Answers (7)

Andreas Kraft
Andreas Kraft

Reputation: 3843

It is also possible to call a constructor from another constructor. See also this answer: How do I call one constructor from another in Java?

And, if you subclass your class, you can call it from the constructor in the subclass via a call to super().

Upvotes: 0

Kaleb Brasee
Kaleb Brasee

Reputation: 51965

This method is a constructor -- it gets called when you create a new NameSurferEntry object and pass a String. You'd call it like this:

NameSurferEntry entry = new NameSurferEntry("some string");

You can tell it's a constructor because the return type is the same as the class name, and there's no method name. It's only callable when you're creating a new NameSurferEntry.

Upvotes: 2

Ritwik Bose
Ritwik Bose

Reputation: 6069

Apologies for before. I saw a phantom void in the constructor. as everyone else has pointed out, it should be

NameSurferEntry nsf = new NameSurferEntry(line);

Upvotes: 0

fforw
fforw

Reputation: 5491

NameSurferEntry is a constructor, not a method. Creating a non-default constructor will hide the default empty constructor. So

// asume line to be a string containing a line
NameSurferEntry entry = new NameSurferEntry(line);

will be the only way to create NameSurferEntry objects.

Upvotes: 3

mopoke
mopoke

Reputation: 10685

NameSurferEntry is the constructor of the class, so you'd do something like:

NameSurferEntry myObject = new NameSurferEntry("value");

Upvotes: 1

Pat
Pat

Reputation: 2238

That's a constructor. You'd call it in the following form:

NameSurferEntry newEntry = new NameSurferEntry("string goes here.");

Upvotes: 0

Mongoose
Mongoose

Reputation: 4645

NameSurferEntry is the constructor of that class, which means it will be called every time you create a new instance of NameSurferEntry with the new operator. There is no other way to call this method.

Upvotes: 1

Related Questions