I’m implementing an interface in Java and was wondering why this code:
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...");
} }
generates the following warning to the left of it:
Package Field
When you implement interfaces, do you gain access to the classes in the package that contain the interface? I have no other files in my package yet and I haven’t done any kind of import either, so I’m actually kind of confused as to why this is accessible to begin with…
Never seen that warning, so going out on a limb here… Do you have a package defined for the class? Otherwise it could mean that the
Thread t-member has what most books call default visibility or package-private visibility (which means package- and class-level visibility), because there’s no visibility modifier for the field. Java has 4 different visibilities: public, default, protected, private. See here for more information: Controlling Access to Members of a Class