Доступ к закрытым членам Java - PullRequest
0 голосов
/ 06 декабря 2018

Я новичок в Java, но я думал, что частные члены могут быть доступны только через публичный метод accessor (например, 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 объявлены как частные в очереди, так почему я могу напрямую получить доступ к этим значениям из конструктора перегрузки?не должен быть доступен только через такой метод, как getQ, getPutLoc, getLoc или что-то подобное?(методы, которые я не реализовал).

1 Ответ

0 голосов
/ 06 декабря 2018

Конструктор также является публичным методом.Вот почему это работает.

...