本文介绍了内部类对象出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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:需要包含YY.inner的封闭实例
YY.inner i = new YY.inner();
^
1错误

InnerYY.java:27: an enclosing instance that contains YY.inner is required YY.inner i = new YY.inner(); ^1 error

推荐答案

您的内部 class是非静态的,因此您必须使用 YY 的实例来实例化它。

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

在您的情况下 Inner inner = ob.new Inner();

请注意:


  • 如果您希望该类公开,您可以将其称为 YY.Inner (但你无法以这种方式实例化)

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

按照惯例你必须使用大写类名(内部而不是内部)。也就是说,我认为值得一提的是,通常在Java中(但这并不像大写的类名称那样必要),开头的大括号保持在同一行。

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.

这篇关于内部类对象出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 20:44