简体   繁体   中英

Call method inside inner class

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

How to call dd() method in main method?

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

To call an instance method, you need an instance of that method eg

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();
    }
}

later

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. You inner class should be in class aa not in method of class aa
  2. And cc class should be static

you can call it using calling bb() call from main like,

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

    new aa().bb()
}

And modify bb()like,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM