如何防止仅在 Java 中堆栈(数组实现)中的索引修改

问题描述 投票:0回答:1

我使用数组创建堆栈,其中有属性 private int index = 0; 在主函数中,当我输入 st.index = 8;和 System.out.println(st.size);那么输出是8,其中“st”是Stack类的对象。

我不希望任何人改变这个索引。为了防止这个问题,我将这个变量设置为私有。但还是可以改变的。

public class Stack_04 {

    public static class StackArray {
        private int[] arr = new int[5];
        private static int index = 0;
    }
    public static void main(String[] args) {
        StackArray st = new StackArray();
        st.index = 8;
        System.out.println(st.index);
    }
}
java arrays indexing stack private
1个回答
0
投票

发生这种情况是因为 StackArray 是一个内部类,因此包含类 Stack_04 可以完全访问该静态内部类中的私有字段,并且由于 main 方法位于 Stack_04 类中,因此它可以在那种情况。

如果您希望它不可访问,您应该考虑将 StackArray 类与 Stack_04 类分开。

public class Stack_04 {
    public static void main(String[] args) {
        StackArray st = new StackArray();
        st.index = 8;
        System.out.println(st.index);
    }
}

class StackArray {
    private int[] arr = new int[5];
    private static int index = 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.