views:

117

answers:

7

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.

+1  A: 

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.

Mongoose
+2  A: 

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.

Kaleb Brasee
A: 

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

NameSurferEntry newEntry = new NameSurferEntry("string goes here.");
Pat
+1  A: 

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

NameSurferEntry myObject = new NameSurferEntry("value");
mopoke
+3  A: 

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.

fforw
A: 

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);
piggles
A: 

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

akr