Reputation: 756
I am trying to make use a class I made, but when I call the class is doesn't work and I am kind of lost.
The error is coming at the class call and initialization of tally at the bottom of the program.
package counter;
public class Counter {
private int value;
public Counter(int intialValue){
value = intialValue;
}
private void count() {
value = value + 1;
}
private void reset(){
value = 0;
}
public int getValue(){
return value;
}
Counter tally = new Counter();
tally.count();
}
Upvotes: 1
Views: 476
Reputation: 96385
From what you've shown so far, it looks like your class Counter has a Counter as an instance member, so that you have an infinite regression trying to instantiate this. You don't give the error but I'd expect a StackOverflowError to result.
That assumes it compiled, which shouldn't happen because the line tally.count() should not be legal. The only things that go into a class are constructor declarations, method declarations, variable declarations, initializer blocks, and nested inner class declarations. The code at the bottom of your class doesn't count as any of those.
Also if you include a constructor with arguments then if you want to call a zero-arg constructor you have to create one explicitly. The code calling the nonexistent zero-arg constructor will cause another compiler error.
So you have a misunderstanding about constructors, plus confusion about what it means to declare things within a class.
Upvotes: 3
Reputation: 34177
All Java statements must be put into a method of some kind.
Currently your last two lines are not in a method.
Counter tally = new Counter();
tally.count();
Try something like this:
public class Counter {
... existing members ...
public static void main(String[] args) {
int initialValue = Integer.parseInt(args[0]);
Counter tally = new Counter(initialValue);
tally.count();
}
}
Upvotes: 7
Reputation: 99
You haven't passed a value into the instance of the class:
Counter tally = new Counter(10);
Or maybe it's because it is not inside a
public static void main(String args)
method body
Upvotes: 0
Reputation: 28727
Counter tally = new Counter();
tally.count();
is outside of any method, this is the error.
Upvotes: 1
Reputation: 46398
tally.count();
should be inside a method body .
public void someMethod() {
tally.count();
}
Also, compiler will not include a default no-args constructor in your class, as you have already written an 1-arg constructor so you will have to pass a valid int value to your constructor.
Counter tally = new Counter(someintval);
Upvotes: 0