Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Lecture 1.docx
Скачиваний:
1
Добавлен:
01.07.2025
Размер:
704 Кб
Скачать
☆

7.2. Defining attributes of objects

Fields of a class specify components of objects of this class. For example, objects representing pairs of integers consist of two integer numbers. It must be noted in the definition of the class Pair. A natural way of doing it is to declare variables of adequate types. public class Pair {         int a;         int b; // definitions of constructors and methods ... } Such notation specifies, that each object of the class Pair contains two integer numbers - it consists of two elements which are integers. The identifiers a and b are arbitrary names necessary to access these numbers. Fields of classes are usually declared with the modifier private, which means that they can be accessed only from within the class in which they are defined. Such fields are not available from methods of other classes.

Defining fields of a class [public] class AClassName {     [field_modifier] type_name variable_name [initializer];     //....          } Note:

  • square brackets specify optional elements of a definition

  • field_modifier is usually private

  • initializer has a well known form: it is an expression preceded by a =; more on this later.

E xample: public class Pair {     private int a;     private int b;     // ... } Fields of a class may be objects (variables specifying objects - references). Consider the definition of a class Book describing books. p ublic class Book {     private String author;     private String title;       private double price;       // .... } The variables of type String are references. They denote adequate objects - strings. The definition of the class Pair states that each its object contains two elements - integers. After an object has been created and initialized it contains two elements - integer numbers with some values. A different object of this class contains some different numbers, with (possibly) different values than the first. What happens, if the values of attributes are set neither by a constructor nor in any other way? They have default values.

By default, during object creation, class fields are set to the value of ZERO:

  • for integer types it means the integer number 0

  • for floating point types it means the real number 0.0.

  • for the type boolean it means the value false

  • for references it is null (reference does not refer to any object)

Therefore, objects of the class Person: class Person {     private String name;     private int age;     private boolean isEmployee; } just after creation have the following values of attributes: name == null, age == 0, isEmployee == false.

7.3. Defining operations on objects (methods)

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_type method_name(parameter_list) {   // ... instructions executed by the method } Notes:

  • the square brackets specify optional elements

  • the source code between the braces is called method body

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

  • the modifier public states that the method can be called from every other class

  • whereas private states that the method can be called only from inside the class it is defined for.

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); } I nvocation 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:

  • add other pairs

  • add to elements of this pair two given numbers

  • add to each element of this pair one given number

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.

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]