-6

Probably I missed something during checking Java core, but please help me to understand why I cannot use method declared in java main method which is commented

class R {
        public int cal(int a, int b) {
            return a + b;
        }

    public int cal3(int a, int b) {
        return a * b;
    }
}

public class Rect {
    public static void main(String arg[]) {

        /*public static int cal2 ( int a, int b){
            return a + b;
        }

        int ab2 = cal2(2,2);
        System.out.println(ab2);*/
        R r = new R();
        int ab = r.cal(2, 2);
        System.out.println(ab);

        int ab3 =r.cal3(2,3);
        System.out.println(ab3);
    }
}
OKie
  • 53
  • 1
  • 6

2 Answers2

1

You cannot declare a method inside another method.

public static int cal2 ( int a, int b){
        return a + b;
}

public static void main(String arg[]) {

    int ab2 = cal2(2);
    System.out.println(ab2);
    R r = new R();
    int ab = r.cal(2, 2);
    System.out.println(ab);

    int ab3 =r.cal3(2,3);
    System.out.println(ab3);
}
sinclair
  • 2,812
  • 4
  • 24
  • 53
1

As others have stated, it is true that you cannot have a typical method defined inside another. But, for clarity, there is an equivalent (Java8 - if that still needs to be stated these days) using the BiFunction interface. For example,

public static void main(String[] args) {
    BiFunction<Integer, Integer, Integer> func = (a, b) -> a + b;
    System.out.println(func.apply(3, 4));
}
ChiefTwoPencils
  • 13,548
  • 8
  • 49
  • 75