gpt4 book ai didi

java - 在java中,嵌套类对象可以使用封闭类方法吗?

转载 作者:行者123 更新时间:2023-12-02 10:13:31 24 4
gpt4 key购买 nike

我创建了一个简单的列表类。我想要做的是在 SLList 中创建一个方法来指定 SLList 对象的大小。我想递归地执行此操作,但是,我创建的以下 size() 方法不起作用。我知道其他实现它的方法,例如创建辅助方法。但我很好奇的是,为什么我的 size() 不起作用?错误消息是“SLList.IntNode 的 size() 未定义”。为什么?既然我将嵌套的 IntMode 类设为公共(public)且非静态,为什么它不能使用 SLList 类中定义的方法?

public class SLList {

public class IntNode {

public int item;
public IntNode next;

public IntNode(int i, IntNode n) {
item = i;
next = n;
}
}

private IntNode first;

public SLList(int x) {
first = new IntNode(x, null);
}

public int size() {
if (first.next == null) {
return 1;
}
return 1 + first.next.size();
}
}

我刚刚接触 Java,对私有(private)和静态的东西很困惑,特别是当涉及到类时。谢谢大家回答我。

最佳答案

您可以通过添加额外的私有(private)方法来修改它,但这并不是特别容易推理。除非绝对必要,否则我会避免这样做。

class SLList {

public class IntNode {

public int item;
public IntNode next;

public IntNode(int i, IntNode n) {
item = i;
next = n;
}

private int theSize()
{
return size();
}
}

private IntNode first;

public SLList(int x) {
first = new IntNode(x, null);
}

public int size() {
if (first.next == null) {
return 1;
}
return 1 + first.next.theSize();
}
}

关于java - 在java中,嵌套类对象可以使用封闭类方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54825969/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com