开发者

error with inner class object

import java.io.*;
class YY
{

   int a=0;
   void putValue(int m)
   {
        a=m;
    inner x=new inner();
        x.display();
   }
   class inner
   {
    void display()
        {
       System.out.println("value of a:"+a);
        }
   }
}

class InnerYY
{
   public static void main(String args[])
   {
    YY ob=new YY();
    ob.putValue(90);
    YY.inner i = new YY.inner();
    i.display();
   }
}

while running this program i'm getting the following error...

InnerYY.java:27开发者_运维技巧: an enclosing instance that contains YY.inner is required YY.inner i = new YY.inner(); ^ 1 error


Your Inner class is non-static, so you havee to instantiate it with an instance of YY.

In your case that is Inner inner = ob.new Inner();

Note that:

  • If you want that class public, you can refer to it as YY.Inner (but you can't instantiate it that way)

  • by convention you must use capitalized class names (Inner rather than inner). That said, I think it's worth mentioning that usually in Java (but that's not as imperative as the capitalized class name) the opening curly bracket stays on the same line.


To reference YY, InnerYY would have to actually be inside YY (moved before the closing break). However you then couldn't have a static main function, which appears to be what it's for.


You try to create non-static inner class from static call YY.inner(). So you need to create object yy = new YY() and then call inner = new yy.inner(). Or to make inner class static.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜