[英]Java private member access
我是 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 或類似的方法訪問嗎? (我還沒有實施的方法)。
構造函數也是一個公共方法。 這就是它起作用的原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.