これは、静的メソッドまたは同様に非静的メンバーにアクセスしている場合にも発生する可能性があります。以下は2つの異なる側面です。1つはエラーを引き起こし、もう1つは解決されたコードの一部です。他のクラスを「静的」にするだけの問題です
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;
}
}
}
これにより、タイプStackArrListの囲んでいるインスタンスにアクセスできませんというエラーがスローされます。StackArrList型の囲んでいるインスタンス(xはStackArrListのインスタンスであるxnew A()など)で割り当てを修飾する必要があります。Stackクラスのインスタンスを作成することはできません
あなたが作るときにクラススタックに静的クラススタックは、罰金を動作し、エラーが存在しません。
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;
}
}
}