Điều này cũng có thể xảy ra nếu bạn đang truy cập các thành viên không tĩnh từ các phương thức tĩnh hoặc tương tự. Sau đây là hai khía cạnh khác nhau, một khía cạnh gây ra lỗi và một đoạn mã đã được giải quyết khác. vấn đề chỉ là làm cho lớp khác dưới dạng "tĩnh"
package Stack;
import java.util.Stack;
import java.util.*;
public class StackArrList {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Stack S = new Stack();
System.out.println("Enter some integers and keep 0 at last:\n");
int n = in.nextInt();
while (n != 0) {
S.push(n);
n = in.nextInt();
}
System.out.println("Numbers in reverse order:\n");
while (!S.empty()) {
System.out.printf("%d", S.pop());
System.out.println("\n");
}
}
public class Stack {
final static int MaxStack = 100;
final static int Value = -999999;
int top = -1;
int[] ST = new int[MaxStack];
public boolean empty() {
return top == -1;
}
public int pop() {
if (this.empty()) {
return Value;
}
int hold = ST[top];
top--;
return hold;
}
public void push(int n) {
if (top == MaxStack - 1) {
System.out.println("\n Stack Overflow\n");
System.exit(1);
}
top++;
ST[top] = n;
}
}
}
Điều này gây ra lỗi Không thể truy cập phiên bản kèm theo của loại StackArrList. Phải đủ điều kiện phân bổ với một phiên bản bao quanh của loại StackArrList (ví dụ :xnew A () trong đó x là một phiên bản của StackArrList). và sẽ không cho phép tạo phiên bản của lớp Stack
Khi bạn làm cho lớp Stack thành lớp tĩnh thì Stack sẽ hoạt động tốt và không có lỗi nào.
package Stack;
import java.util.Stack;
import java.util.*;
public class StackArrList {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Stack S = new Stack();
System.out.println("Enter some integers and keep 0 at last:\n");
int n = in.nextInt();
while (n != 0) {
S.push(n);
n = in.nextInt();
}
System.out.println("Numbers in reverse order:\n");
while (!S.empty()) {
System.out.printf("%d", S.pop());
System.out.println("\n");
}
}
static class Stack {
final static int MaxStack = 100;
final static int Value = -999999;
int top = -1;
int[] ST = new int[MaxStack];
public boolean empty() {
return top == -1;
}
public int pop() {
if (this.empty()) {
return Value;
}
int hold = ST[top];
top--;
return hold;
}
public void push(int n) {
if (top == MaxStack - 1) {
System.out.println("\n Stack Overflow\n");
System.exit(1);
}
top++;
ST[top] = n;
}
}
}