1

I have declared a function in a class and want to know if I could define it outside the class. I have seen these cases in C++ but haven't come across anything like this in Java. Does Java allows doing this?

5
  • Everything in Java needs to be inside a class Commented Sep 18, 2015 at 22:57
  • @CoryRoy interface too? :P Commented Sep 18, 2015 at 22:58
  • @alfasin You are correct, class or interface. Commented Sep 18, 2015 at 23:00
  • @alfasin enum also,trolling :D Commented Sep 18, 2015 at 23:03
  • @KumarAbhinav if you want to be a real wiseass you should say that it doesn't apply to a... class, as well :))) Commented Sep 18, 2015 at 23:20

3 Answers 3

7

No you can't.

Java requires a single top level class for each file (eg. class Foo in Foo.java), named as the file. Everything must reside inside that class.

Sign up to request clarification or add additional context in comments.

Comments

1

I have declared a function in a class and want to know if I could define it outside the class. I have seen these cases in C++ but haven't come across anything like this in Java. Does Java allows doing this?

No, you can't do that outside a class. This is similar as asking whether we can write some codes without a class at all. Everything is done within a class in Java.

If no class exist, then at least it will be an interface.

Example:

class{ void method(){} } interface{ void methodA(); default void method(){} } 

Comments

0

Everyone above is right, the function will be out of scope in java, in c++ you can declare functions as global and such, but java everything has to be inside of the class, unless you are working with an interface

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.