Java私有成员访问权

时间:2018-12-06 03:43:38

标签: java oop object member

我是Java的初学者,但我认为只能通过“访问器”公共方法(例如get或set)访问私有成员,所以这使我感到困扰:

class Queue {

    private char[] q;
    private int putloc, getloc; // the put and get indices

    // Construct an empty queue given its size
    Queue(int size) {
        this.q = new char[size];
        this.putloc = this.getloc = 0;
    }

    // Construct a queue from a queue
    Queue(Queue ob) {
        this.putloc = ob.putloc;
        this.getloc = ob.getloc;

        this.q = new char[ob.q.length];

        // copy elements
        for(int i=this.getloc; i<this.putloc; i++) {
            this.q[i] = ob.q[i];
        }
    }

    // Construct a queue with initial values
    Queue(char[] a) {
        this.putloc = 0;
        this.getloc = 0;
        this.q = new char[a.length];

        for(int i=0; i<a.length; i++) this.put(a[i]);
    }

    // Put a character into the queue
    void put(char ch) {
        if (this.putloc == q.length) {
            System.out.println(" - Queue is full");
            return;
        }

        q[this.putloc++] = ch;
    }

    // Get character from the queue
    char get() {
        if (this.getloc == this.putloc) {
            System.out.println(" - Queue is empty");
            return (char) 0;
        }

        return this.q[this.getloc++];
    }

    void print() {
        for(char ch: this.q) {
            System.out.println(ch);
        }
    }
}

UseQueue是一个单独的文件:

class UseQueue {

    public static void main(String args[]) {
        System.out.println("Queue Program");

        // Construct 10-element empty queue
        Queue q1 = new Queue(10);
        System.out.println("Q1: ");
        q1.print();

        char[] name = {'S', 'e', 'b', 'a', 's'};
        // Construct queue from array
        Queue q2 = new Queue(name);
        System.out.println("Q2: ");
        q2.print();

        // put some chars into q1
        for(int i=0; i<10; i++) {
            q1.put((char) ('A' + i));
        }

        System.out.println("Q1 after adding chars: ");
        q1.print();

        // Construct new queue from another queue
        Queue q3 = new Queue(q1);
        System.out.println("Q3 built from Q1: ");
        q3.print();

    }
}

如您所见,q,putloc和getloc在Queue中被声明为私有,那么为什么我可以直接从重载构造函数访问这些值?不应仅通过诸如getQ,getPutLoc,getLoc之类的方法访问? (我尚未实现的方法)。

1 个答案:

答案 0 :(得分:1)

构造函数也是一个公共方法。这就是为什么它起作用。