Студопедия
Случайная страница | ТОМ-1 | ТОМ-2 | ТОМ-3
АрхитектураБиологияГеографияДругоеИностранные языки
ИнформатикаИсторияКультураЛитератураМатематика
МедицинаМеханикаОбразованиеОхрана трудаПедагогика
ПолитикаПравоПрограммированиеПсихологияРелигия
СоциологияСпортСтроительствоФизикаФилософия
ФинансыХимияЭкологияЭкономикаЭлектроника

Defining operations on objects (methods)

Write down and run this program on your computer | Introduction to objects | The first program | Types. Primitive types. | Types of variables. Declarations. | More on operators and expressions | Numeric promotions | Objects and references | The class String | Useful examples |


Читайте также:
  1. Article 17. Exchange Operations with Foreign Currency
  2. Article 22. Participation in Authorized Capital, and Operations with Securities and Derivative Financial Instruments
  3. Article 7. Licensing of Currency Operations
  4. C) Defining the Operational Level Agreements for the technical teams
  5. Cargo operations
  6. Chapter 2. Defining Love and Its Permutations
  7. Classes and objects

The definition of a class specifies the set of messages understood by an object.
The notion of a method is similar to the already familiar notion of function.

A method - similarly to a function - is a separate sequence of instructions, noted once in a source code, which can be called (invoked) repeatedly from various points in a program.

 

Methods are used mainly (but not only) to carry out operations on objects.

Therefore, methods - as opposed to functions - are usually called for concrete, existing objects.

 

The invocation of a method for an object is done with the help of the dot operator. If p denotes an object of the class Pair (p is a reference to an object of the class Pair), and if the method show is defined in this class, then the invocation of this method for the object p is noted as:

p.show();

"Calling (invoking) a method for an object" means the same as "sending a message to an object" or "making request of an object".
In this case (for the method show):

invocation of the method show for the object p
=
sending of the message show to the object p
=
request for showing the object p

 

The syntax of the definition of a method is:

[ access_modifier ] result_typemethod_name (parameter_list) {
//... instructions executed by the method
}

Notes:

 

An access modifier specifies whether the method can be called from outside the class it is defined. In particular:

Method names start with small letters (according to the Hungarian notation), for example: count, setPrice, getAuthor.

The methods accessible for everybody are specified with the modifier public. The methods, which perform local operations, important only for other methods of this class and not for anybody else, should be declared private.

The list of parameters contains declarations of parameters separated with commas. It may be empty.

A method may return a value. Its definition should then declare the type of the result and termination of its execution should be caused by the instruction return (which returns data of the specified type). If the method does not return any value, then the type of its result is specified with the keyword void. It can terminate after executing all of the instructions in method body or as result of return without any arguments.

The return statement has the following form:

return [ expression ];

 

For example, a method returning the sum of two integers may look like this:

int sum(int x, int y) {
int z = x + y;
return z;
}

or:

int sum(int x, int y) {
return x + y;
}

By its invocation the method sum gets its arguments as the parameters x and y. Its execution consists in adding the two numbers and returning the result. The type of the result must be specified in the definition of the method.

Another example:

void say(String s) {
System.out.println(s);
}

Invocation of the method say causes printing of the string given as argument to the command prompt. It does not return any value, but still the result type must be specified (with the keyword void).


In Java arguments are passed to methods by value.
It means that inside the method body we operate on the copy of the argument, not the argument itself. Therefore, modifications of the passed argument are local - they do not affect the original.

Thus, after calling the following method:

void incr(int x) {
++x;
}

with the variable z = 1 passed as the argument, the argument (parameter) x inside the method body gets value 2. However, after completing method invocation and returning control to the point of invocation, the variable z still stores the value of 1.

The same rule holds for reference types.
It does not mean that we cannot operate on objects inside methods. We can do it by accessing fields directly or by calling methods which modify fields (more on this later).


A class may define methods with the same name, but differing in the number and/or types of parameters.
It is called overloading of methods.
What is it used for?
Assume we want to carry out the following operations on objects of the class Pair:


If there was no possibility of method overloading, we would have to make up a different name for each of the above methods. But the essence of these operations is similar, so the name add should be good for all.

Thanks to overloading we can define in the class Pair the following methods:

void add(Pair p) // to the pair for which the method was called
// adds the pair given as argument
void add(int i) // adds the given number to both components of the pair
void add(int i, int k) // the first of the given numbers is added to the first component of the pair
// and the second number is added to the second component

and use them somewhere else in a natural way

Pair p;.
Pair somePair;
....
p.add(3); // the method which fits best to the given arguments is chosen
p.add(1,2);
p.add(somePair);

The identifiers of the methods defined in a class must differ.
The exceptions to the above rule are overloaded methods. They have the same name, but different types and/or the number of arguments.

 


Дата добавления: 2015-11-16; просмотров: 59 | Нарушение авторских прав


<== предыдущая страница | следующая страница ==>
Defining attributes of objects| Defining methods of object creation (constructors)

mybiblioteka.su - 2015-2024 год. (0.008 сек.)