java - 接口(interface)和封装

标签 java interface

我正在用 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/

相关文章:

java - 如何使用 sbt-assembly 插件设置 build.sbt?

java - 第一次实现java接口(interface),无法编译成功

java - Antlr4.6 BaseVisitor 和 Visitor 错误 : Visitor (Interface) is abstract; cannot be instantiated BaseVisitor (Class) & super() error

java - 仅出于履行契约(Contract)的目的而在方法签名中包含 args 是否是常见的做法

Java - 从文本文件加载二叉树

java - 从 src 目录打开文件 (Java)

java - 如何获得架构支持的最小的 next 或 previous 可能的 double 值?

java - Hibernate 在 db 中查找现有对象

在界面中使用枚举的 typescript

pointers - 如果它作为接口(interface)传递,则访问指针值{}