内部类中的调用方法

时间:2015-11-30 07:49:36

标签: java methods

class aa {
  public void bb() {
    class cc {
      public void dd() {
        System.out.println("hello");
      }
    }
  }
}

如何在main方法中调用dd()方法?

class Solution {
  public static void main(String arg[]) {
    /* i want to call dd() here */    
  }
}

3 个答案:

答案 0 :(得分:2)

要调用实例方法,您需要该方法的实例,例如

class aa {
    interface ii {
        public void dd();
    }

    public ii bb() {
        // you can only call the method of a public interface or class
        // as cc implements ii, this allows you to call the method.
        class cc implements ii {
             public void dd() {
                  System.out.println("hello");   
             }
        }
        return new cc();
    }
}

new aa().bb().dd();

答案 1 :(得分:0)

class aa {
    public void bb() {

    }

    static class  cc {
        void dd() {
            System.out.println("hello");
        }
    }

    public static void main(String[] args) {
        cc c = new aa.cc();
        c.dd();
    }
}
  1. 你的内部课堂应该在班级aa而不是班级aa的方法
  2. cc类应该是静态的

答案 2 :(得分:0)

您可以使用来自main的调用bb()调用来调用它,

public static void main(String... s){

    new aa().bb()
}

修改bb(),

public void bb()
    {
       class cc{
           public void dd()
              {
                 System.out.println("hello");   
              }
     } 
       new cc().dd();
    }