簡體   English   中英

如何從 starter class 中的方法訪問私有 integer(在嵌套類中聲明)?

[英]How do you access a private integer (declared in a nested class) from a method within the starter class?

我見過很多關於訪問私有方法的問題,但沒有看到關於訪問私有整數的問題,所以我認為這值得一問。 基本上,我有我的主要 class RunnyStack,以及一個名為 Run 的私有嵌套 class。 在 Run 內部,我初始化了一個私有 integer,長度,我試圖從 RunnyStack 中的一個方法訪問這個私有 int。

我已經嘗試過搜索這個問題(太久了),我發現的答案對我不起作用,因為(根據 class 指令)我需要在 Run 中將長度聲明為私有 int。 這意味着(根據我的嘗試)我不能執行“Run hello = new Run();”,因為它說“構造函數 RunnyStack.Run() 未定義”。我還嘗試了“RunnyStack.Run len = new RunnyStack” .Run();',但它只是說'構造函數 RunnyStack.Run() 未定義'

    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;
    }
}

此代碼顯示嵌套私有 class 的創建,包括私有 integer 長度。

    public void push(Base base) {
    if(isEmpty()) {
        top = new Run(base, top);
    }
    else {
        if(base == top) {
            length += 1;
        }
    }
}

這段代碼顯示了我試圖訪問長度的方法

我要做的就是訪問長度,以便在滿足 if 語句時可以增加它。 任何幫助表示贊賞,謝謝!

Run class 里面,創建一個 getter 方法:

foo getFoo(){ // Cannot be private
    return this.foo;
}

另外:二傳手

void setFoo(Foo f){ // Also cannot be private
    this.foo = f;
}

您需要實現一個getter方法 - 這些通常是可以訪問私有字段的public方法。

格式通常是

public field-type getFieldName () {
  return fieldname;
}

所以就長度而言

public int getLength () {
    return length;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM