I've seen lots of questions about accessing private methods, but none about accessing private integers, so I figured this was worth asking. Basically, I have my main class, RunnyStack, with a private nested class called Run. Inside Run, I initialized a private integer, length, and I'm trying to access this private int from a method inside RunnyStack.
I've already tried searching up this problem (for too long), and the answers I found don't work for me, because (per class instructions) I need to declare length as a private int inside Run. This means (from what I've tried) I cannot do 'Run hello = new Run();", because it says 'The constructor RunnyStack.Run() is undefined'. I also tried 'RunnyStack.Run len = new RunnyStack.Run();', but it just said 'The constructor RunnyStack.Run() is undefined'
class RunnyStack<Base> {
private class Run {
private Base base;
private Run next;
private int length;
private Run(Base base, Run next) {
this.base = base;
this.next = next;
this.length = 0;
}
}
This code shows the creation of the nested private class, including the private integer length.
public void push(Base base) {
if(isEmpty()) {
top = new Run(base, top);
}
else {
if(base == top) {
length += 1;
}
}
}
This code shows the method I'm trying to access length in
All I want to do is access length so that I can increase it whenever the if statement is fulfilled. Any help is appreciated, thanks!
Inside the Run
class, create a getter method:
foo getFoo(){ // Cannot be private
return this.foo;
}
Also: Setters
void setFoo(Foo f){ // Also cannot be private
this.foo = f;
}
You need to implement a getter
method - these are usually public
methods which can access the private fields.
The format is usually
public field-type getFieldName () {
return fieldname;
}
so for length it would be
public int getLength () {
return length;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.