[英]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.