Pages

Sunday, June 10, 2012

Methods


In this lesson we are going to study the methods. The methods becomes from the classes. They can change some propeties of the classes or the can obtain some value or functionalities of a class. Every method can have one or more arguments passed by the user, and can return a value or not. The methods can be public, private or protected. A public method can be called from a main programm where the class is constructed. A private method can only be called in the owner class. And the protected methods are method that can be called internally and from any subclass method. The subclasses will be discussed in another lesson. The variables can also be public, private or protected. Both methods and variables can be defined without specifying the visibility, here they will take the default visibility, private.

Structure of a method:

[visibility] [data returned] [name] ([data type of argument 1] [name of argument 1], [data type of argument 2] [name of argument 2]...){
[...]
}

Example:
public int getInteger(int argument1){
//something
return 1;
}

The constructor are methods too, but they are called only when the class is instancied. We can differenciate it from other methods because the constructor must have the same name as the class and it do not return anything. One class can have more than one constructor but they must be different by anyone of them from the arguments they have.

Here is an example:
public class ObjectA{
//variables
private String v1;
private int v2;
//constructor 1
public ObjectA(){
this.v1 = "Hello";
this.v2 = 0;
}
//constructor 2
public ObjectA(String arg1, int arg2){
this.v1 = arg1;
this.v2 = arg2;
}
//public method
public int getV2Incremented(){
this.v2 = this.increment(this.v2);
return this.v2;
}
//private method
private int increment(int value){
return value++;
}
}

No comments:

Post a Comment