0

Why this happened, it gives me error in void main when initializing newString, this The method StringThread(String, int) is undefined for the type mainThread ? Here is code:

public class mainThread {

    public class StringThread implements Runnable {

        private int num;
        private String text;

        public StringThread(String text, int num){
            this.text = text;
            this.num = num;
        }

        public void run(){
            for(int i = 0; i < num;i++)
                System.out.println(i+1+". " + text);
        }

    }

    public static void main(String[] args){
        StringThread newString;
        newString  = StringThread("Java", 30);
        new Thread(newString).start();
    }

}

2 Answers2

1
 StringThread newString = new mainThread().new StringThread("Java", 30);

You didn't initialize it oO

12dollar
  • 645
  • 3
  • 17
0

new keyword is missing in your initialization and that's why it is considering it as a method and not constructor and as it's inner class it should be. (Suggested by Stultuske)

mainThread obj = new mainThread();
StringThread newString = new obj.StringThread("Java", 30);//new keyword is missing

Please read following answer to understand why we need to do this to access inner class,

Community
  • 1
  • 1
akash
  • 22,664
  • 11
  • 59
  • 87
  • Actually, it needs to be: new mainThread().new StringThread("Java", 30); – Stultuske Jul 14 '15 at 13:58
  • Thanks, so silly stupid mistake, but now it say:No enclosing instance of type mainThread is accessible. Must qualify the allocation with an enclosing instance of type mainThread (e.g. x.new A() where x is an instance of mainThread). – Stefan Eftan Jul 14 '15 at 13:59
  • Stefan: that is why I added my comment. You need to go through an instance of mainThread, since your StringThread class is located within mainThread, and the static main method belongs to mainThread. – Stultuske Jul 14 '15 at 14:00