-3

the first example is possible, but example 2 is not possible and results in "illegal start of expression" error message from the compiler. why is it not possible to define a method inside of the run() method?

example 1

 public class TextUpdater implements Runnable {

    public void inter(){

    }

    @Override
    public void run() {

        inter();

    }

   }
}

example 2, not possible

 public class TextUpdater implements Runnable {

    @Override
    public void run() {

       public void inter(){  // results in error

       }

   }
}
user
  • 86,916
  • 18
  • 197
  • 190
Kevik
  • 9,181
  • 19
  • 92
  • 148

5 Answers5

4

Java does not let you define a method inside a method. It doesn't even have any semantic rules for what that would do. What are you expecting example 2 to do?

It's clear what example 1 does. You create a method called inter with an empty body. Then, in run, you call it.

But what should 2 do? You create a method inter inside run. So what would that do? When would you call it?

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
1

Because you cannot define a method inside a method.

Maroun
  • 94,125
  • 30
  • 188
  • 241
1

If you actually declare a method within a method it will always result in an error. Java is strictly object-oriented and it requires methods to belong to a class. In other words, you have to declare your methods in class. JavaScript, Python and other object-oriented languages loosen this strict rule, but Java does not. Read this thread on stackoverflow. It is almost exactly the same topic.

Community
  • 1
  • 1
Florian R. Klein
  • 1,375
  • 2
  • 15
  • 32
0

Not possible to create a method inside another method.

AppX
  • 528
  • 2
  • 12
0

run() is a method, you just can not define new methods inside a method. Methods are defining in class section not inside methods

Lebedevsd
  • 950
  • 5
  • 12