Question

My code looks like this:

public class Hello{

    private class Word{ 
        ... 
    }

    public static void main(String[] args) {

        Word W = new Hello.Word();
    }
}

How can I call the class Word from main?

Word W = new Hello.Word(); 

seems not to be the right solution.

Was it helpful?

Solution 2

You are trying to instantiate non-static class inside another, from a static context.

Either make the inner class static:

 private static class Word{ 
    ... 
 }

(However, you wouldn't need the Hello part, just Word W = new Word(); would do perfectly)

Or create an instance of the outer class, and then create an instance of the inner class using that. (Sotirios suggested this solution too, but with better details.)

OTHER TIPS

You can do

Hello.Word word = new Hello().new Word();

Since Word is an inner class, you need an instance of the outer class to instantiate it.

Word is inner class of Hello,i.e., without existing of Hello class instance there no chance of Word class instance existence. so you have to create an object Hello first and then Word object.
Try this

    Hello.Word W =  new Hello(). new Word();  
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top