我正在用 Java 实现一个接口(interface),并且想知道为什么这段代码:
package threaddemo;
// Create a new thread...
class NewThread implements Runnable {
Thread t;
NewThread(){
// Create a second, new thread...
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start();
}
// This is the entry point for the second thread...
public void run(){
try {
for (int i=0; i<5; i++){
System.out.println("Child thread: " + i);
// Let the thread sleep for a while...
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted...");
}
System.out.println("Exiting child thread...");
} }
public class ThreadDemo {
public static void main(String[] args) {
// Create a new thread...
new NewThread();
try {
for (int i=0; i<5; i++){
System.out.println("Main thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e){
System.out.println("Main thread itnerrupted...");
}
System.out.println("Main thread exiting...");
} }
在其左侧生成以下警告:
Package Field
当您实现接口(interface)时,您是否可以访问包含该接口(interface)的包中的类?我的包中还没有其他文件,也没有进行任何类型的导入,所以我实际上有点困惑为什么这是可以访问的......
最佳答案
从来没有见过这个警告,所以在这里冒险...你有为该类定义的包吗?否则,这可能意味着 Thread t 成员具有大多数书籍所称的默认可见性或包私有(private)可见性(这意味着包级和类级可见性),因为该字段没有可见性修饰符。 Java 有 4 种不同的可见性:公共(public)、默认、 protected 、私有(private)。请参阅此处了解更多信息:Controlling Access to Members of a Class
关于java - 接口(interface)和封装,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12209164/