Prakash Bala
Prakash Bala

Reputation: 1

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 */    
  }
}

Upvotes: 0

Views: 78

Answers (3)

Peter Lawrey
Peter Lawrey

Reputation: 533880

To call an instance method, you need an instance of that method e.g.

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

Upvotes: 2

Vishal Gajera
Vishal Gajera

Reputation: 4207

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

Upvotes: 0

Ahmed
Ahmed

Reputation: 184

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

Upvotes: 0

Related Questions