Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Declare now, define Later

In java can you declare a method in a class and then either define it later in the class or outside of the class?

I am looking for something similar to C++ where you declare it then use the :: format outside the class to define it later?

Also, not overloading the method.

like image 293
wondernate Avatar asked Feb 21 '23 18:02

wondernate


1 Answers

C++ member functions are never defined "outside of the class". The Class_Name:: prefix puts them inside the class. They are just not in the class declaration.

Splitting declarations and definitions is made necessary in C++ because the separate compilation model is based on text file inclusion. The detailed information about a class cannot be pulled from the compiled object file, so a condensed summary of the type information is factored out into a header file, and that must be included by all client modules of that class. Java has a more sophisticated object file format which makes it possible to get information about a class without a header file.

Another need for declarations that arises in languages is to handle cases of mutual recursion between functions or oother forms of circular reference (for instance they are needed in the Wirth's original Pascal language which had no support for splitting a program into separate modules). Java works out mutual recursion without requiring forward declarations. You just have to defer type checking until a full parse. Forward declarations in Pascal are not there to make mutual recursion possible, but to make it possible to compile it in one pass, whereby you can emit the code for one function before compiling the next one. (This is important when your hardware was built in 1968.)

If you're using a language which makes declarations unnecessary, why bother to look for a way to put them back in? It's like continuing to eat prison food after you've been released. (This may be an instance of "learned helplessness".)

Anyway, the state of the art in type systems for decades now has been marked by designs that avoid declarations as much as possible and rely instead on type inference. Look at how many times you have to write the class name in C++ to get anything done. class myclass { public: myclass(); }; myclass::myclass() { /* constructor */ }. Four repetitions of myclass just to make a dummy class that does nothing, with a constructor that is defined outside of the class declaration.

like image 93
Kaz Avatar answered Feb 27 '23 09:02

Kaz