Saturday, March 22, 2014

Error - creating an instance of an inner class
























Java Code:




















package Threads;

// THIS PROGRAM WILL HAVE TWO THREADS i.e. "main" AND ANOTHER THREAD (SYSTEM WILL NAME IT "Thread-0"
//THE STORY IS THAT WE WILL START Thread-0 FROM main AND LET IT EXECUTE.
//main WILL WAIT AND LET IT EXECUTE FOR 5 MINUTES.
//IF IT FINISHES ITS EXECUTION BEFORE 5 MINUTES, WELL AND GOOD;
//BUT IF IT DOESN'T, WE WILL INTERRUPT IT.
//AFTER INTERRUPTION, WE WILL DECIDE TO WAIT INDEFINITELY.

public class SimpleThreadsCopy {
public static void threadMessage(String s){
String sThreadName= Thread.currentThread().getName();
System.out.format("%s: %s%n", sThreadName, s);
}
public class MessageLoop implements Runnable{
public void run(){
String foodChain[]= {"Mares eat oats", "Doves eat oats", "Little lambs eat ivy", "A kid will eat ivy too" };
try{for (int i=0; i<foodChain.length; i++){
threadMessage(foodChain[i]);
Thread.sleep(6000);
}
}catch(Exception e){
threadMessage("I have been interrupted.");
}
}
}
public static void main(String [] args){
threadMessage("STARTING THE THREAD NAMED MessageLoop!");//Announces that we are going to start the MessageLoop thead
long timeTaken= 1000 * 60 * 5;
long startTime = System.currentTimeMillis();
Thread t= new Thread(new MessageLoop()); //**************************************************ERROR
t.start();
threadMessage("Waiting for MessageLoop to finish execution!");
while(t.isAlive()){
threadMessage("Still waiting...");//just says that the main thread is waiting for MessageLoop to complete, till 5 minutes
try{t.join(1000);}catch(Exception e){threadMessage("t.join(1000); statement interrupted.");}
if(System.currentTimeMillis() - startTime > timeTaken && t.isAlive()){
t.interrupt();
try{t.join();}catch(Exception e){threadMessage("t.join(); statement interrupted.");} // waits indefinitely
}
}
}
}


















The statement against which I have written many *'s gives the following error.







No enclosing instance of type SimpleThreadsCopy is accessible. Must qualify the allocation with an enclosing instance of type SimpleThreadsCopy (e.g. x.new A() where x is an instance of SimpleThreadsCopy).
















Now that a similar "error-free" code is given here, what's wrong with this piece of code and what should I do about it?
















EDIT:- Trying to understand the error statement, I replaced the erroneous statement with
























Java Code:




















Thread t= new Thread(new SimpleThreadsCopy().new MessageLoop());


















and the error got fixed. From that I understand that the inner class is just kinda a nonstatic member of the outer class and it will be accessed by the objects of the outer class only.







But then why doesn't the code in the tutorial give an error?































No comments:

Post a Comment