Results 1 to 7 of 7
Like Tree2Likes
  • 1 Post By JosAH
  • 1 Post By jim829

Thread: Error - creating an instance of an inner class

  1. #1
    Zarah is offline Senior Member
    Join Date
    Mar 2014
    Posts
    116
    Rep Power
    0

    Default 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?
    Last edited by Zarah; 03-22-2014 at 09:36 AM.

  2. #2
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,529
    Blog Entries
    7
    Rep Power
    20

    Default Re: Error - creating an instance of an inner class

    I think the example defined MessageLoop as a statically nested class ...

    kind regards,

    Jos
    Zarah likes this.
    cenosillicaphobia: the fear for an empty beer glass

  3. #3
    jim829 is online now Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,617
    Rep Power
    5

    Default Re: Error - creating an instance of an inner class

    Here's a recommendation. When you enter main, which is a static method, you can have problems doing certain things
    related to instances of the enclosing class. As such, I very seldom do anything in main except something like the following:

    Assume a class named MyClass.

    Java Code:
    public static void main(String[] args) {
        new MyClass().start();
    }
    
    public void start() {
      // put here what you would
    // normally put in main
    }
    I recommend reading up on static vs non-static contexts. If you have questions about it the forum will be here to help.

    Regards,
    Jim
    Zarah likes this.
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  4. #4
    karthikeyan is offline Member
    Join Date
    Mar 2014
    Posts
    1
    Rep Power
    0

    Default Re: Error - creating an instance of an inner class

    its quite easy. you need not to use the key word static in the method "threadMessage" Bcz u r creating an object for class "SimpleThreadsCopy" so you need not put static

  5. #5
    jim829 is online now Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,617
    Rep Power
    5

    Default Re: Error - creating an instance of an inner class

    That has nothing to do with the OP's problem and introduces even more error in the code. And just because one creates instances of classes does not mean those classes should not contain static methods. After all, main is a static method.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  6. #6
    Zarah is offline Senior Member
    Join Date
    Mar 2014
    Posts
    116
    Rep Power
    0

    Default Re: Error - creating an instance of an inner class

    Quote Originally Posted by JosAH View Post
    I think the example defined MessageLoop as a statically nested class ...

    kind regards,

    Jos
    Oh yes, I overlooked that, my bad.

  7. #7
    Zarah is offline Senior Member
    Join Date
    Mar 2014
    Posts
    116
    Rep Power
    0

    Default Re: Error - creating an instance of an inner class

    Quote Originally Posted by jim829 View Post
    Here's a recommendation. When you enter main, which is a static method, you can have problems doing certain things
    related to instances of the enclosing class. As such, I very seldom do anything in main except something like the following:

    Assume a class named MyClass.

    Java Code:
    public static void main(String[] args) {
        new MyClass().start();
    }
    
    public void start() {
      // put here what you would
    // normally put in main
    }
    I recommend reading up on static vs non-static contexts. If you have questions about it the forum will be here to help.

    Regards,
    Jim
    Thank you, since I have faced the nemesis of "non-static method can not be called from static context", I will definitely like to take up your recommendation.

    I am reading about static vs non-static variables and methods.

Similar Threads

  1. Replies: 2
    Last Post: 09-16-2013, 04:19 PM
  2. Replies: 1
    Last Post: 04-21-2012, 06:03 PM
  3. error in creating the entity class by netbeans
    By javastuden in forum NetBeans
    Replies: 2
    Last Post: 07-22-2011, 01:29 PM
  4. Finding and Creating Instance of Every Class in Package
    By Julian Trust in forum New To Java
    Replies: 5
    Last Post: 06-25-2011, 08:34 AM
  5. Help with creating an instance of a class extension
    By Inferno719 in forum New To Java
    Replies: 19
    Last Post: 05-04-2011, 03:53 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •