這些天我正在使用 CS61b。我被訪問控制的講座困住了。我的變量first和類IntNode上的“private”關鍵字無法正常工作。在谷歌上搜索但一無所獲。public class SLList { private IntNode first; /** * If the nested class never uses any instance variables or methods of the outer * class, declare it static. */ private static class IntNode { public IntNode next; public int item; public IntNode(int i, IntNode n) { next = n; item = i; } } public SLList(int x) { first = new IntNode(x, null); } public void addFirst(int x) { first = new IntNode(x, first); } public int getFirst() { return first.item; }/** ----------------SIZE---------------------- */ private int size(IntNode L) { if (L.next == null) { return 1; } return 1 + size(L.next); } public int size() { return size(first); }/**-------------------SIZE------------------- *//**---------------add LAST ------------------*//** how to solve null pointer expectation? */ public void addLast(int x) { IntNode p=first; while(p.next!=null){ p=p.next; } p.next=new IntNode(x, null); }/**---------------add LAST ------------------*/ public static void main(String[] args) { SLList L = new SLList(5); L.addFirst(10); L.addFirst(15); System.out.println(L.getFirst()); System.out.println(L.size()); L.addLast(20); L.first.next.next = L.first.next; /** <----- I can still get√ access to first. */ }}我預計會出現錯誤:first has private class in SLList,但我沒有任何錯誤。
1 回答

郎朗坤
TA貢獻1921條經驗 獲得超9個贊
僅當類型可訪問并且聲明成員或構造函數允許訪問時,引用類型的成員(類、接口、字段或方法)或類類型的構造函數才可訪問:
(強調我的)
由于您的訪問first
位于同一頂級類型內,因此您可以毫無問題、錯誤或任何其他情況地訪問它。
添加回答
舉報
0/150
提交
取消