Reputation: 27
Here's the API/UML that I have to follow.
And here's my code.
public class NLP
{
private String[] data;
public NLP() //or "public NLP(String[] data)"???
{
// IF public NLP(String[] data), then
//this.data = data; ???
...
}
public int countOccurrences(String word)
{
...
return count;
}
public String[] getStems(int len)
{
...return data; //???
}
//For testing
//public static void main(String[] args)
//{
//}
}
I'm not sure if my constructor is supposed to be public NLP(String[] data)
or public NLP()
. If public NLP(String[] data)
is supposed to be my constructor instead, can someone explain to me why there are two (String[] data)
's?
Here's my completed code. Feel free to check and give feedbacks. Thanks.
public class NLP
{
private String[] data;
public NLP(String[] data)
{
this.data = data;
}
public int countOccurrences(String word)
{
int count = 0;
for (int i = 0; i < data.length; i++)
{
if (word.equals(data[i]))
{
count = count + 1;
}
}
StdOut.println(word + ": " + count);
return count;
}
public String[] getStems(int len)
{
for (int i = 0; i < data.length; i++)
{
String s = data[i];
if (len >= data[i].length())
{
data[i] = s;
StdOut.println(data[i]);
}
if (len < data[i].length())
{
data[i] = s.substring(0, len);
StdOut.println(data[i]);
}
}return data;
}
}
Upvotes: 1
Views: 68
Reputation: 541
In a UML class diagram, the middle section (in your case, the one with "- String [] data") contains the class's fields, and the bottom section (with "+ NLP(String [] data)") contains the classes methods, of which the constructor is technically one. Here is a quick reference that I quite like.
As such, it would appear that your constructor should be public NLP(String[] data)
and inside of it, you will set this.data = data
.
Upvotes: 1
Reputation: 2813
The constructor is supposed to include the argument (i.e. public NLP(String[] data)
) as shown in the API description, so in my opinion your implementation (as given in the lower part of the question) is just fine.
However, I think that your general question is about how the constructor and internal data of your class are related:
The data (or state) of the class is kept in one or more variables (sometimes also called members, fields, or attributes) - in your case String[] data
. A general concept in object-oriented programming is to keep the members private and to access them only via public interface methods (such as getters and setters). This is known as encapsulation.
Defining a constructor without an argument is of course also possible, but it could only initialize the class with some fixed values. In your case, the intention is to initialize the internal member data
with the argument passed to the constructor (which happens to also be named data
).
Finally, many programming languages (including Java) allow overloading of constructors, so you could for example have one constructor with arguments and another one without arguments. Here is a helpful introduction.
Upvotes: 1