What is the OOPs concept in C.

6Object-oriented programming

This chapter describes the basics of object-oriented programming and provides an introduction to Java. Advanced readers who already have experience in Java programming and only want to learn how to use leJOS and the EV3 by reading this book can proceed as follows:

Both the EV3 and the computer used are fully set up at this point and the EV3 sample programs from Chapter 7, Chapter 8, Chapter 10 and Chapter 11 can be transferred and executed. Understanding these example programs and the description of the available leJOS classes in Chapter 10 provide a good basis for starting programming your own robots.

The Galileo Openbook "Java is also an island", which can be viewed free of charge on the Internet, can be recommended as general basic Java reading. Even if »Java is also an island« does not deal specifically with leJOS and the EV3, important basics for programming with Java are described in a clear and easily understandable way. [17]

6.1 General information on object orientation

The term "object orientation" describes a type of modeling in software development. In very simplified terms, this is to be understood as the abstraction of the real world and the transfer of this abstracted model to a machine. However, it is still possible to program procedurally (division of tasks and sub-problems into procedures), as is done in C, for example. The concept of object orientation (OO for short) offers many advantages that fundamentally change and simplify the development of software. Attempts are made to use human structuring and classification methods.

Object orientation is based on a division of the world to be described into objects with their properties and operations. This division is implemented through the concept of the class, in which objects are grouped together based on similar properties and encapsulated from the outside. The structure of an object is determined by the attributes (including properties) of its class definition. The behavior of the object is determined by the methods of the class.

6.1.1 Advantages of object orientation

One advantage of the object-oriented programming paradigm, object-oriented programming (OOP for short), is the possibility of reusing program parts. Consistently developed program parts can be used in different con fi gurations and different logical contexts. Another advantage is that the program to be generated can be divided into clear program sections. Their creation and maintenance can thus be structured better and more transparently.

The different parts of the program are therefore independent of one another and can be developed individually and by different people. In order to bene fi t from the advantages described, the following four concepts are used:

  • Generalization
  • Inheritance
  • Encapsulation
  • Polymorphism

These four concepts are described in Chapter 7.

6.2 Basic structures of the OOP

Before these concepts can be discussed, the basic structures of object-oriented programming are presented.

6.2.1 Classes

As mentioned at the beginning, the concept of OOP is strongly based on structuring and classification methods from the everyday (human) view of our real world. The following example should clarify this:

The term ff passenger car represents a classification of motorized vehicles which (mostly four-wheeled) are used to transport people from A to B. The term does not define the number of doors, color, shape, cubic capacity, etc. of the car.

A similar example related to the topic of this book is offered by the term robot:

In the traditional sense, a robot is a technical device that has been designed to take on human tasks in order to relieve them. Many different types can be distinguished, for example in terms of appearance: humanoid robots, industrial robots, mobile robots, etc. Also other properties such as area of ​​application, costs, task or the number of axes are not defined.

This type of structuring is used by object-oriented programming through the use of classes and objects. Applied to the examples, the classes and are created in order to determine which attributes a later created object of the class should have. The object then represents something that actually exists with concrete attribute values, e.g. the yellow VW Beetle from Mr. Müller or the industrial robot from the automobile company Ford.

The following example shows how the class is de fi ned in Java.


Program 6.1: ExampleRobot class

1publicclassExampleRobot {
2 // variables:
3publicStringname;
4publicdoubleprice;
5publicintyearOfPurchase;
6publicStringappearance;
7
8 // methods:
9publicintage (intcurrentYear) {
10returncurrentYear-yearOfPurchase;
11}
12}

The class definition is started by the keyword. Any number of variables and method definitions can be entered in the curly brackets. The variables (also called attributes of a class) store the properties of the class - here description (), costs (), year of purchase () and appearance (). The methods de fi ne the capabilities or behavior of objects. In the example, the method can be used to return the age of the corresponding robot. Methods are created within classes and can access the class attributes. The so-called modifier and others are explained in Chapter 7 under the heading Encapsulation.

Since software is often developed by international teams, variables and methods are named and source text comments are written in English. We agree with this practice, but the German translations are still given in the text.

6.2.2 Objects

An object (or instance1) is a concrete expression of a class. If an object is created by a class, it receives all attributes and methods that are contained in this class. Furthermore, all objects have three important properties:

  • Every object has a state.
  • Every object shows behavior.
  • Every object has an identity.

The current values ​​of the variables of an object form its state. This can change in the course of a program. The behavior of an object is formed by its methods. Among other things, they define how the object can change its state or the state of other objects. In addition, each object has its own, unchangeable identity internally. Even if two objects of a class have the same state and show the same behavior, they are still different objects with different identities.

6.2.3 Create an object

To create an object, a variable of the type of the class (here) must be declared. A newly created object is then assigned to this variable with the operator. The object is created using the operator, followed by the class name with two round brackets (i.e.). This expression is called the default constructor and is described in Section 6.3.


Program 6.2: Create the object

1publicclassExampleRobot {
2publicStringname;
3publicdoubleprice;
4publicintyearOfPurchase;
5publicStringappearance;
6
7publicintage (intcurrentYear) {
8returncurrentYear-yearOfPurchase;
9}
10
11publicstaticvoidmain (String [] args) {
12ExampleRobotmyEV3;
13myEV3 = newExampleRobot ();
14}
15}

The object is created using the so-called method. This represents the main program in a class file and is also described in Section 6.3.

The declaration of a variable and the assignment of an object can also be combined in one line:
In the last example program, there is an object of the class. This specific robot () has the general attributes of the class: name (), cost (), year of purchase () and appearance (). But it does not yet have any manifestations, that is, an undefined state. The following state is now established in the example program 6.3:
  • Name: LEGO EV3
  • Cost: 319.95
  • Year of purchase: 2013
  • Appearance: Roberta

This is done by using the operator, which can be used to access variables and methods of an object.


Program 6.3: Initialize the object variables

1publicclassExampleRobot {
2publicStringname;
3publicdoubleprice;
4publicintyearOfPurchase;
5publicStringappearance;
6
7publicintage (intcurrentYear) {
8returncurrentYear-yearOfPurchase;
9}
10
11publicstaticvoidmain (String [] args) {
12ExampleRobotmyEV3;
13myEV3 = newExampleRobot ();
14
15myEV3.name = "LEGOEV3";
16myEV3.price = 319.95;
17myEV3.yearOfPurchase = 2013;
18myEV3.appearance = "Roberta";
19}
20}

6.3 General program structures

Every program needs a basic structure. Just like in other programming languages, this structure is fixed and must be observed. This chapter is intended to give a brief overview of the various elements that must appear in a class.

6.3.1 File structure

The program structure of a leJOS program is quite simple. Care should be taken to adhere to some guidelines and conventions. It is customary to create a public class (which is declared with a keyword) in every file. Any number of other helper classes can then be found in the file, but none of them are public. The file name corresponds to the class name of the public class. The class is also saved in the file.

6.3.2 Package import

Every Java program uses certain libraries. This describes the commands that are to be used during programming. When programming with leJOS, the classes for sensors and motors etc. from the respective packages must be integrated so that the Java program code can be understood and implemented correctly. If you want to include the CLASS CLASS from the PACKAGE package, this works according to the following basic principle:

For example, if the class »EV3ColorSensor« from the package »lejos.hardware.sensor« is to be used to control the EV3 color sensor, the command is:

importlejos.hardware.sensor.EV3ColorSensor;

If you want to directly integrate several classes from a package, for example the leJOS classes for controlling all sensors, the operator is used:

importlejos.hardware.sensor. *;

Eclipse supports the developers in integrating the classes with a hint if classes are to be used that have not yet been integrated. Eclipse automatically adds the required line to the program code by simply left-clicking on the corresponding note.

6.3.3 End of class

After the package imports, the actual class is de fi ned. A new public class is created with the keywords. In our example this is:

publicclassExampleRobot

Then the class body begins, which is enclosed in curly brackets (see for example program 6.3).

6.3.4 The main method

Once the basic structure has been created, the main function that bears the name is now required. This method is also of the type and since it is a class method, it still gets the keyword. In our example this is:

publicstaticvoidmain (String [] args)

A string array (i.e. a field variable of the string type) must always be transferred to the function. The field in which the class name itself is in the first place is transferred. The start parameters can be found in the following places. The main function can now accommodate the entire program, create other objects or start threads (see Section 8.3). Once the function has been processed, the program execution on the EV3 also ends automatically. However, if a class is only there to instantiate objects of its type, it has no method. Instead there is a so-called constructor.

6.3.5 Constructor

The Constructor is called every time an object is instantiated. It can be described as a kind of special method with no return value. This method is firmly linked to the class and bears its name. With the execution of the constructor, for example, initial values ​​can be set or counter variables can be increased. The constructor is called when an object is created with the keyword (see program 6.4). This means that the constructor is called exactly once for each object. A subsequent or renewed call is not possible. In addition to constructors, there are also destructors in Java that are called before an object is destroyed. Since Java has automatic memory management, no further importance is attached to destructors in this book.

In the next example program, the robot's variables are not initialized in the method, but in a specially created constructor.


Program 6.4: ExampleRobot with constructor

1/∗∗
2 ∗ ExampleRobot − class.
3 ∗ Objectisbeingcreatedinmain − method
4 ∗ andvariablesareinitializedwithaspecificconstructor.
5∗/
6publicclassExampleRobot {
7publicStringname;
8publicdoubleprice;
9publicintyearOfPurchase;
10publicStringappearance;
11
12publicintage (intcurrentYear) {
13returncurrentYear-yearOfPurchase;
14}
15
16ExampleRobot (Stringname, doubleprice, intyearOfPurchase, Stringappearance) {
17this.name = name;
18this.price = price;
19this.yearOfPurchase = yearOfPurchase;
20this.appearance = appearance;
21}
22
23publicstaticvoidmain (String [] args) {
24ExampleRobotmyEV3;
25myEV3 = newExampleRobot ("LEGOEV3", 319.95,2013, "Roberta");
26}
27}

When creating the object with the operator, the variable values ​​are passed to the constructor as parameters, separated by commas. In the construct definition, you can then specify what is to be done with the values ​​transferred in this way. In our case they are assigned to the variables of the object. So that there is no confusion between parameter names and variable names, the latter are identified by the so-called - pointer. This always refers to the object to which the method (or the constructor) belongs.

6.3.6Default constructor

If no explicit constructor is specified when creating a class, the compiler automatically creates a default constructor that is called without specifying parameters.

6.3.7 Java code conventions

The Java code conventions set out rules with regard to the form of Java source code. It is advisable to adhere to these rules, as this allows developers to find their way into foreign code more quickly and increases readability. The code convention documentation published by Java can be viewed at http://www.oracle.com/technetwork/java/codeconvtoc-136057.html. The most important conventions are presented below:

  • The code is indented by 4 spaces for each new block. Eclipse usually indents automatically with the correct spacing, otherwise the tabulator can also be used.
  • If an expression does not fit on a line, it is broken after a comma or before an operator.
  • One line should be used for each variable declaration.
  • Local variables should be initialized when they are declared (only possible if the value does not have to be calculated).
  • The initialization is placed at the beginning of a block.
  • Each line should contain at most one statement.
  • Class names should be nouns with capital letters. The so-called CamelCase is generally used in Java. This means that internal words in an identifier are capitalized again. For example: KlassenNameImCamelCase.
  • Interface identifiers are chosen like class names.
  • Methods should be verbs and start with a lowercase letter. The camelCase is also used for methods, albeit with a lowercase letter. For example: methodNameImCamelCase.
  • Variable names are formatted like method names. They should be short and meaningful about the function of the variable.
  • Constant names consist exclusively of capital letters. Individual words are separated by an underscore. For example: ONE_CONSTANT.

6.3.8 Comments and Javadoc

In Java, as in most programming languages, there are several ways to add comments to your source code. The simplest is the so-called line comment. A comment is introduced at any point in the source text by inserting a comment. All characters that appear afterwards in this line are not translated by the compiler. The comment ends with the line.

The second option is to use what are known as block comments. These start with anywhere in the source code and end with. All characters in between are ignored by the compiler. Block comments can also span multiple lines.

Comments can also be used to comment out program parts for test purposes and thus not to compile them. In contrast to deleting the program lines, they can then simply be commented in again if they are to be used again.
Commenting on source code is an often neglected but important part of software development, since code is usually read more often than it is written. Especially if program components are to be made available to other developers, they must be well documented. The creation of external documentation for the source code used to be done manually. This was very time-consuming and error-prone, since all changes in the source code also had to be implemented in the documentation.

Nowadays, such external documentation is created automatically, mostly in HTML format. With Java this task is done by the program »Javadoc«. For this purpose, special documentation comments are used in front of every class, every interface, every constructor, every method and every attribute. These describe the corresponding element and are converted into the documentation by Javadoc. Documentation comments are a special form of block comments. They start with and end with. Lines in between usually begin with a, which visually enhances the comment but does not fulfill any other function.

The first sentence of each documentation comment appears in the summary of methods and attributes. This first sentence should, if possible, completely describe the functionality. The entire documentation comment is then listed in the detail view. When describing the methods, it should rather be stated that What the method does as how she does it. Parameters and return values ​​should also be specified. So-called "tags" are used for this, with which a large amount of information can be transferred to "Javadoc" within a documentation comment. Table 6.1 provides an overview of the most important tags.

Day

description

use

Description of a parameter

Description of the return value

Reference to each other package / method / attribute

/

Specification of the exception that the method can throw

Author's statement

Indicates that the method is obsolete and should no longer be used

Table 6.1 .: Javadoc tags

Javadoc documentation can be created in Eclipse via File → Export and selecting »Javadoc« in the »Java« category. In order to clarify the use of such documentation, sample program 6.4 has been completely provided with Javadoc comments:


Program 6.5: ExampleRobot with constructor (Javadoc)

1/∗∗
2 ∗ ExampleRobot − class.
3 ∗ Objectisbeingcreatedinmain − method
4 ∗ andvariablesareinitializedwithanondefault − constructor.
5∗/
6publicclassExampleRobot {
7/∗∗
8 ∗ Nameoftherobot
9∗/
10publicStringname;
11/∗∗
12 ∗ Priceoftherobot
13∗/
14publicdoubleprice;
15/∗∗
16 ∗ Yeartherobotwasboughtin
17∗/
18publicintyearOfPurchase;
19/∗∗
20 ∗ Appearance soft herobot
21∗/
22publicStringappearance;
23/∗∗
24 ∗ Returnstheageoftherobot.
25 ∗ @ paramcurrentYearThecurrentyear
26 ∗ @ returnTheageoftherobot
27∗/
28publicintage (intcurrentYear) {
29returncurrentYear-yearOfPurchase;
30}
31/∗∗
32 ∗ Constructor, thatinitializestheinstance − variableswithgivenparameters
33 ∗ @ paramnameNameoftherobot
34 ∗ @ parampricePriceoftherobot
35 ∗ @ paramyearOfPurchaseYeartherobotwasboughtin
36 ∗ @ paramappearanceAppearanceoftherobot
37∗/
38ExampleRobot (Stringname, doubleprice, intyearOfPurchase, Stringappearance) {
39this.name = name;
40this.price = price;
41this.yearOfPurchase = yearOfPurchase;
42this.appearance = appearance;
43}
44/∗∗
45 ∗ main − method.Objectiscreatedhere.
46 ∗ @ paramargsstandardparameterformain − method
47∗/
48publicstaticvoidmain (String [] args) {
49ExampleRobotmyEV3;
50myEV3 = newExampleRobot ("LEGOEV3", 319.95,2013, "Roberta");
51}
52}

6.4 Variables and methods

6.4.1 Variables

The basic functionality of variables does not differ from that of other programming languages. Table 6.2 gives an overview of the data types with which variables can be assigned and which leJOS provides. The following is the difference between

  • Instance variables
  • Class variables
  • local variables

become clear.

Depending on the way in which a variable is declared, it is either an instance (instance), a class (class) or a local variable (local variable). A Instance variable is, as the name suggests, a variable that is only available to the object created together with it. A Class variable however, it is available to all objects of a class. So if, as described in the example, some objects are created by a class, they get the properties from this class. Although there is only one attribute (appearance) in the class, every object (i.e. every concrete robot) can describe and change this value individually without affecting the other objects.

However, if it is to be recorded, for example, how many objects of the class have been created, the class needs a counter that all objects can access. This counter is then a Class variable: The content of the variable is the same for all instances. Such a variable is identified by the keyword when it is declared.