user2889632
user2889632

Reputation:

How to call inner class method inside the main method?

I am creating a class Perfect inside the main class and in Perfect class i am creating a method perf() and i want to call this method in the main method..how to do it?

My code is here

public class Fib {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub


            }

    class Perfect {

        void perf(){
            int sum = 0;
            int count = 0;

            for(int i=6; i<=10000; i++){
                for(int j=1; j<=i/2; j++){
                    if(i%j==0){
                        sum+=j;
                    }
                }
                if(sum==i){
                    count=count+1;
                    System.out.println(i);
                }
                sum=0;
            }

            System.out.println("Total perfect number is : "+count);

        }
    }
}

Upvotes: 1

Views: 665

Answers (3)

Wanna Coffee
Wanna Coffee

Reputation: 2798

You can call inner class method inside the main method.

you have to make inner class as static, then you can directly access by className.MethodName(). There is not a necessity of creating object..

Example:

package com;

public class Fib {
    public static void main(String[] args) {
        Perfect.assign(5);
       }

   private static class Perfect {      
       static void assign(int i) {
           System.out.println("value i : "+i);
       }

    }
}

Here, Perfect is inner class, assign is a method which is place inside inner class... Now i just call inner class method by className.MethodName().

When you run this program you will get an Output: value i : 5

Hope this helps.!!

Upvotes: 0

Toon Borgers
Toon Borgers

Reputation: 3658

new Fib().new Perfect().perf() should work fine

Upvotes: 3

Danyal
Danyal

Reputation: 370

You can write in this form

    Fib outer = new Fib();
    Perfect inner = outer.new Perfect (); 
    System.out.println(inner.perf());

Upvotes: 0

Related Questions