Results 1 to 2 of 2
  1. #1
    jvmakela is offline Member
    Join Date
    Oct 2010
    Posts
    1
    Rep Power
    0

    Default Private inner & Runnable class instantiation failure

    // What is wrong this code?

    public class PingPong
    {
    ...
    public static void main(String[] args)
    {
    PingPong application = new PingPong(args);
    Thread t1 = new Thread(new WaitTask());
    Thread t2 = new Thread(new SocketTask());
    t1.start();
    t2.start();
    }

    class WaitTask implements Runnable
    {
    public WaitTask()
    {}
    public void run()
    {}
    }

    class SocketTask implements Runnable
    {
    public SocketTask()
    {}
    public void run()
    {}
    }
    }

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

    and compilation gives:

    C:\Data\workspace\ApplAndServ\src>javac PingPong.java
    PingPong.java:130: non-static variable this cannot be referenced from a static context
    Thread t1 = new Thread(new WaitTask());
    ^
    PingPong.java:131: non-static variable this cannot be referenced from a static context
    Thread t2 = new Thread(new SocketTask());
    ^
    2 errors

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

    Default

    Those two classes are 'inner' classes which means that you can only create an object of those classes when there is an object of the outer class. The inner class objects 'belong' to the outer class object. Think of them as moons and an object of the outer class as the planet. When there's no planet there can't be moons.

    If you don't want that you should make those classes static; those sort of classes are called 'nested' classes and if they're public you can create an object of those classes without the need for an object of the outer class.

    kind regards,

    Jos

Similar Threads

  1. Why make class variables private?
    By PrinceSendai in forum New To Java
    Replies: 3
    Last Post: 10-18-2010, 11:01 AM
  2. Replies: 12
    Last Post: 08-02-2010, 02:39 PM
  3. Public, private or (nothing) class
    By tyang in forum New To Java
    Replies: 3
    Last Post: 01-31-2010, 11:37 PM
  4. Replies: 3
    Last Post: 03-14-2009, 07:22 AM
  5. Replies: 1
    Last Post: 03-14-2008, 02:51 PM

Posting Permissions

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