今天上午学习了下Java 的Stack类。写了几行代码,想打印出栈里面的元素个数,使用父类的size()方法没有出现错误,但是想访问父类里的protected 变量elementCount的值,却报错了。
我疑惑不解的是,java的访问修饰符,protected修饰的成员,在子类中是可以访问的。
代码以及编译器报错:
-------------------------------------我是分隔符---------------------------------------
package com.practice.javaDataStructure;
import static java.lang.System.out;
import java.util.Iterator;
import java.util.Stack;
public class StackMethods {
public static void main(String[] args){
Stack<String> sk = new Stack<String>();
// 1. empty()
boolean isEmpty = sk.empty();
out.println("empty : "+isEmpty );
// size or number of elements in stack
out.printf("the size of stack is %d\n", sk.size());
// 2. push()
String pushElement = sk.push("first");
out.println("pushElement : " + pushElement);
sk.push("second");
sk.push("third");
// iterator and output , indicate sequence from bottom to top , add sequence
Iterator<String> it = sk.iterator();
out.println("now iterator ------");
while(it.hasNext()){
out.println(it.next());
}
// size or number of elements in stack
out.printf("the size of stack is %d\n",sk.size());
//out.printf("the size of stack is %d", sk.elementCount); // Error:(34, 49) java: elementCount has protected access in java.util.Vector
// 3. peek()
String peekElement = sk.peek();
out.println("peekElement : " + peekElement);
// size or number of elements in stack
out.printf("the size of stack is %d\n", sk.size());
// 4. pop()
String popElement = sk.pop();
out.println("popElement : " + popElement);
// size or number of elements in stack
out.printf("the size of stack is %d\n", sk.size());
// 5. search()
out.println("now search ----");
int search1 = sk.search("first");
out.println("search1 : "+search1);
int search2 = sk.search("second");
out.println("search2 : "+search2);
int search3 = sk.search("third");
out.println("search3 : "+search3);
// 1. empty()
boolean isEmpty1 = sk.empty();
out.println("empty : "+isEmpty1 );
}
}
你是在StackMethods这个类中访问elementCount的哦,而StackMethods并不是Vector的子类,所以报错了。
在子类中可以访问,用子类的实例引用来访问,这是两会事,初开始的确有点不好理解。
protected修饰的成员,在子类中是可以访问的,楼主的描述没有错,但关键在于“子类中”楼主理解错了意思
只能在子类的内部访问的含义:只能在Stack里面访问父类的protect属性,外部包括你的StackMethods类的任何地方是不允许调用的,除了Statck类自己