Showing posts with label Method (computer science). Show all posts
Showing posts with label Method (computer science). Show all posts

Sunday, 15 May 2011

Differences between methods and constructors.

  • There is no return type given in a constructor signature (header). The value is this object itself so there is no need to indicate a return value.
  • There is no return statement in the body of the constructor.
  • The first line of a constructor must either be a call on another constructor in the same class (using this), or a call on the superclass constructor (using super). If the first line is neither of these, the compiler automatically inserts a call to the parameterless super class constructor.
These differences in syntax between a constructor and method are sometimes hard to see when looking at the source. It would have been better to have had a keyword to clearly mark constructors as some languages do.

Thursday, 21 April 2011

Passing by value vs pass by reference

Argument Passing
When a simple type is passed to a method, it is done by use of call-by-value. Objects are passed by use of call-by-reference.
So when object is passed,  it is passed as reference.

Returning objects
Let Test be a class, and

class Test {
    int a;
      Test(int i) {
          a = i;
       }
   Test increase {
    Test temp = new Test(a+10);
    return temp;
  }
}


As you can see, each time increase( ) is invoked, a new object is created, and a
reference to it is returned to the calling routine.
The preceding program makes another important point: Since all objects are
dynamically allocated using new, you don’t need to worry about an object going
out-of-scope because the method in which it was created terminates. The object will
continue to exist as long as there is a reference to it somewhere in your program.
When there are no references to it, the object will be reclaimed the next time garbage
collection takes place.
Java supports recursion.




Types of Methods in java

Constructor methods allow class objects to be created with fields initialized to values as determined by the methods' parameters. This allows objects to start with values appropriate to use (eg. salary set to a base level or employeeNumber set to an incrementing value to guarantee uniqueness). For our simple box class:
public Box() {length=0;width=0;height=0;} // default is point
public Box(int l,int w,int h) // allows giving initial size
{length=l; width=w; height=h;}
Note that there is no class keyword or return datatype keyword. Also the method name is the same as the class name. This is what marks the fragment as a constructor method. If no constructor method is defined for a class, a default constructor is automatically used to initialize all fields to 0, false or unicode(0) as appropriate to the datatype.
One clever programming device is to declare the constructor with no parameters as private and use it to initialize all properties. Then other constructors can first call it using this() and then do their own specific property validations/initialization.
Accessor (or observer) methods read property (ie. field variable) values and are conventionally named getFoobar() or whatever the property is called.
Mutator (or transformer) methods set property values and are often named setFoobar() etc. Mutators can be used to ensure that the property's value is valid in both range and type.
It is good programming practice to make each property in a class private and include accessor and mutator methods for them. This is an example of object encapsulization. The exceptions to writing accessor/mutator methods for each property is for those that are used only within the class itself or for properties that are set in more complex ways.
Helper methods are those routines that are useful within the class methods but not outside the class. They can help in code modularization. Normally they are assigned private access to restrict use.
Recursive methods are methods that are defined in terms of themselves. A classic recursion is factorials where n factorial is the product of positive integer n and all the products before it down to one. In Java this could be programmed as:
class Factorial
{
int factorial(int n)
{
if (n==1){return 1};
return (n*factorial(n-1));
}
}
Caution: This short method is not very well written as negative and floating calling parameters are illegal in factorials and will cause problems in terminating the loop. Bad input should always be trapped.

Continue, Break and Return

Continue statements are used in looping statements to force another iteration of the loop before reaching the end of the current one. Most often continue is used as part of a conditional statement that only happens in certain cases. The following is a trivial example.
int x=0;
while (x<10)
{
x++;
System.out.println(x);
continue;
// you will never get to this point!!
};
Break statements are used in looping and 'switch' statements to force an abrupt termination or exit from the loop or switch. In the following example the loop is never completed. Once again the normal use of break is as part of a conditional statement.
int x=0;
while (x<10)
{
x++;
System.out.println(x);
break;
// you will never get to this point!
};
Return statements are used to force a quick exit from a method. They are also used to pass values back from methods.

Methods of java vs Functions of c++

All stand-alone C++ programs require a function named main and can have numerous other functions, including both stand-alone functions and functions, which are members of a class. There are no stand-alone functions in Java. Instead, there are only functions that are members of a class, usually called methods. Global functions and global data are not allowed in Java.
All function or method definitions in Java are contained within the class definition. To a C++ programmer, they may look like inline function definitions, but they aren't. Java doesn't allow the programmer to request that a function be made inline, at least not directly.
Both C++ and Java support class (static) methods or functions that can be called without the requirement to instantiate an object of the class.
In C++, static data members and functions are called using the name of the class and the name of the static member connected by the scope resolution operator. In Java, the dot is used for this purpose.
C++ requires that classes and functions be declared before they are used. This is not necessary in Java.
Like C++, Java allows you to overload functions. However, default arguments are not supported by Java.
Unlike C++, Java does not support templates. Thus, there are no generic functions or classes.
As in C++, Java applications can call functions written in another language. This is commonly referred to as native methods. However, applets cannot call native methods.
Java 5 adds support for variable length argument lists

Sunday, 26 September 2010

Static Inner Classes

Consider the following Java code fragment:
public class A
{
int y;

public static class B
{
int x;

void f () {}
}
}
This fragment defines the class A which contains an static inner class B. A static inner class behaves like any ``outer'' class. It may contain methods and fields, and it may be instantiated like this:
A.B object = new A.B ();
This statement creates an new instance of the inner class B.
Given such an instance, we can invoke the f method in the usual way:
object.f();
 
Note:
It is not necessarily the case that an instance of the outer class A exists even when we have created an instance of the inner class. Similarly, instantiating the outer class A does not create any instances of the inner class B.
The methods of a static inner class may access all the members (fields or methods) of the inner class but they can access only static members (fields or methods) of the outer class. Thus, f can access the field x, but it cannot access the field y.

Saturday, 12 December 2009

Functions or Methods in java

Class behaviour are represented in Java by methods. To declare a method use the following syntax:
[ "public" | "private" | "protected" ] [ "final" ]
[ "static" | "abstract" | "native" ]
return_data_type method_name "(" parameter_list ")"
"{"
// some defining actions
"}"
Accessibility keywords are the same as for properties. The default (ie. omitted) is package (aka friendly) or visible within the current package only.
static methods are shared by all members and exist for all runtime. Static methods can be referenced without creating an instance of the class. abstract methods must be redefined on inheritance. native methods are written in C but accessible from Java.
The return_data_type defines the type of value that the calling routine receives from the object (the reply message in object terminology). It can be any of the primitive types or the reserved word void (default value) if no message is to be returned. The statement return varName; is used to declare the value to be returned to the calling routine.
The parameter_list can contain from zero to many entries of datatype varName pairs. Entries are separated by commas. Parameters are passed by value, thus upholding the encapsulation principle by not allowing unexpected changes or side effects. Object references (such as arrays) can also be passed.
Some examples of method header parameter lists are:
 
public static void example1() {}
public static int add2(int x) {x+=2; return x;}
public static double example3(int x, double d) {return x*d;}
public static void example4(int x, int y, boolean flag) {}
public static void example5(int arr[]) {} // note: this is object

Note: Differences from cpp 
Types of methods
Pass by value or reference