簡體   English   中英

內部類中的調用方法

[英]Call method inside inner class

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

如何在主方法中調用dd()方法?

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

要調用實例方法,您需要該方法的實例,例如

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();
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類應該是靜態的

您可以使用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();
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM