Stefan Eftan
Stefan Eftan

Reputation: 25

From static main method in same outer class like inner class, can't access to constructor from inner class

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();
    }

}

Upvotes: 0

Views: 65

Answers (2)

Akash Thakare
Akash Thakare

Reputation: 22972

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,

Upvotes: 0

12dollar
12dollar

Reputation: 655

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

You didn't initialize it oO

Upvotes: 1

Related Questions