Functions and Methods


Functions and Methods

In C they are called functions. Java calls them methods. Both are named blocks of code that can be called from somewhere else in a program. Functions are the basic building blocks of a C program. Java methods, on the other hand, are always declared inside of a class. Java methods do not have to be prototyped.

A C function declaration includes the return type, function name , and input parameter list. The only modifying keywords that can be applied to a C function are extern , which means the function is defined outside of the current file, or static , which means the function cannot be referenced from other files. The body of the function is enclosed in braces.

Java method declarations contain the return type, name, and input parameter list of the method. The declaration may also include modifying keywords and a throws clause. Java methods are more powerful and versatile than their C counterparts. For one thing, Java methods can be given an access modifier. This keyword defines how and when the method can be accessed by other code. Java methods can be declared to be static , abstract , final , native , and synchronized . As with C, the body of a Java method is enclosed in braces.

Input arguments are passed to a C function by value, meaning that a copy of the value of the variable is sent to the function. Any changes made to the variable inside the function will not be reflected in the original variable. To have a C function alter the value of the original variable, a pointer to the variable must be passed to the function.

Arguments to Java methods are also passed by value. For arguments representing primitive types, a copy of the argument value is sent to the method. Any changes made to the value inside the method will not be made to the original value. For arguments representing reference types (objects or arrays), a copy of the reference to the location in memory where the data for the object or array is stored is sent to the method. Any changes made to the object inside the method will also be made to the original object.

C functions are called by simply typing the function name and providing the appropriate arguments. The way that Java methods are called depends on where the method call occurs. Inside the class in which they are defined, Java methods can be called by typing the method name and providing the appropriate arguments. Outside of the class in which they are defined, Java methods are called relative to a class instance or the class name depending on whether it is an instance or static method.



Technical Java. Applications for Science and Engineering
Technical Java: Applications for Science and Engineering
ISBN: 0131018159
EAN: 2147483647
Year: 2003
Pages: 281
Authors: Grant Palmer

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net