-1

Java program on thread, it seems to be alright but there's something wrong at UserThread ut1 = new UserThread(5, "Thread A");

Program:

public class Ch10_2_2 {

    class UserThread extends Thread {
        private int length;
        public UserThread(int length, String name){
            super(name);
            this.length = length;
        }

        public void run() {
            int temp = 0;
            for (int i = 1; i <= length; i++)   temp += i;
            System.out.println(Thread.currentThread() + "Sum = " + temp);
        }
    }

    public static void main(String[] args) {
        System.out.println("Thread: " + Thread.currentThread());

        UserThread ut1 = new UserThread(5, "Thread A");
        UserThread ut2 = new UserThread(5, "Thread B");

        ut1.start();    ut2.start();
    }
}

Error message:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: No enclosing instance of type Ch10_2_2 is accessible. Must qualify the allocation with an enclosing instance of type Ch10_2_2 (e.g. x.new A() where x is an instance of Ch10_2_2). at Ch10_2_2.main(Ch10_2_2.java:21)

Iłya Bursov
  • 23,342
  • 4
  • 33
  • 57
Snowman
  • 59
  • 1
  • 10

1 Answers1

0

You should change your UserThread class to be static.

Currently, you're trying to access an "instance" class from a static context, which is invalid. Making your nested class static will allow you to access it from a static context without error.

See this question for more information.

Community
  • 1
  • 1
blacktide
  • 10,654
  • 8
  • 33
  • 53
  • Why was this downvoted? This is the correct solution. – blacktide Feb 26 '16 at 02:44
  • If the `inner` class is static then there will only be `one` right? As the OP is instantiating two of them in a non thread-safe manner, then this is not the solution that he wants. – Scary Wombat Feb 26 '16 at 02:52
  • @Scary Wombat : That is incorrect. Whether a class is defined as static or not there will only be one definition of it in the ClassLoader. The difference is in how you reference that definition. If a nested class is not static it cannot be referenced directly. An instance of the outer class is required i.e. `NestedClass c = new OuterClass().new NestedClass() ` – BevynQ Feb 28 '16 at 21:20