Technology

Overview: 
Introduction to access control modifier keywords.
Objectives: 

Gain a basic understanding of access control modifiers.

Content: 

You have seen the access control modifier public used extensively in our Java examples. The access control modifier is applied to classes and class members (variables and methods) and determines what access code in other classes have to the class members.

Classes can have no access modifier before the class name and will default to package-private. This means the class is only visible to top level classes in the same package. You can also use public, which means the class is visible inside and outside of its package.

At the member level, things get a bit more complicated. You can use access modifiers of public, private, protected or the default, package-private (when no modifier is specified).

  • public - The member is accessible to the world.
  • private - The member is accessible only in the same class it is defined.
  • protected - The member is accessible only in classes defined in the same package or any subclasses thereof.
  • package-private - The member is accessible only to other classes in the same package but not in subclasses. Again, this is the default when no access modifier is specified.

In robotics, using public for everything will work fine. Access modifiers are typically important when creating libraries that will be shared with other projects. In those cases, there may be internal members that should not be exposed to users of the library.

Here is a video about access control. We will discuss access control in more detail in a later lesson.

 

Navigation:

Overview: 
Explore the basics of objects and classes.
Objectives: 

Understand what objects and classes are and a basic idea of how to use them.

Content: 

Java is an object-oriented language so it stands to reason that objects are the workhorse construct of the language. We have talked about objects and classes in previous lessons but now its time start our detailed exploration of objects.

An object is a software container that includes state information (variables) and behaviors (methods). Objects are used to model real-world things like cars, people, bank accounts, etc. Joysticks, controllers, Motors, servos, and sensors are all typically going to be objects in robot code.

A class is a prototype or blueprint for an object from which actual object instances are created. Object and class can be used interchangeably and that is fine but there is a difference. We write a class as source code in a .java file and then use that class definition in another .java file to create an instance of the object defined by the class with the new keyword. The basic form of a class definition is:

We will discuss modifiers later, for now we use the word public. This means other classes can access this class. The keyword class is required and the name of the class followed by the class body as a statement block. Here is a simple class definition for a real world object, your dog:

We see the Dog class has state information in the variables breed, name and age. These are also called fields. We have made the fields public so we can access them directly from other code. At this point, we have not created any particular instance of a ‘dog’ object, we have just said “All Dogs will have a breed, name, and age.” The only constraint we have is that the breed and name both have to be strings, and the age has to be an integer.

We also see a method that implements a behavior of dogs. With this class you have created your own custom Data Type called Dog. So in another place in your code you might write:

The new keyword creates a new object instance of the Dog Data Type (class) and puts a reference to that instance into the variable myDog. myDog now points to a Dog object instance, which you can manipulate.

We access the components of the Dog object with the . (dot) notation. We use the myDog variable name followed by a dot and then the name of a Dog class component (field or method) we want to access. So, if we want to use the function bark(), we must state myDog.bark(), as opposed to just bark(). The method bark() is owned by the class Dog, and when writing code that is outside of the class Dog, we must access the method bark() by having a Dog object instance to call it with. With a robot motor, for instance, we would create an instance of the Motor class connecting it to an actual motor, store it in variable motorA and then write motorA.setPower(0.5) to set our motorA object instance to half power.

An most significant feature of objects is the ability to use multiple objects all created from the single class definition:

In a robot example, if we have four motors on our robot, we would create four instances of the motor class.
 
Here is more about objects, classes and using objects. Here are two videos (video1, video2) discussing objects and classes.

Note that, while not required, it is considered good programming practice to make all class fields private. This means that fields cannot be directly accessed with the dot notation. In this case, you must provide methods to set and get the values of fields. The reason is to make sure the values of fields are always under the control of the class methods and so the methods can then depend on the values being correct since no outside code can modify them directly. To follow this convention we would rewrite our Dog class like this:

Here we provide methods to give code using our class access to set and get the name and breed fields. Note that in the setName() method, we used a parameter called name. If we did nothing about this the compiler would not be able to tell the class field called name from the method parameter called name. The this. keyword allows us to tell the compiler when we want the class level field. You can think of the this. keyword as meaning "class level".

Following that idea, if we have a variable in a method with the same name as a class level field, the variable in the method "hides" the class level field. This means any use of the variable name refers to the method local variable. If we wish to do this and still need to access the class level field, we again use the this. keyword to tell the compiler we mean the class level field.

We also include a constructor method (more later) that allows us to set the dog name when we create an instance with the new keyword. We would use this new Dog class as follows:

Here are the examples on CodingGround (old) and here on CodingGround (new). Read below before looking at the examples. Add a Cat class with field name and breed and a method called meow() and call it from the main method.

It is a Java convention to have each class is in a separate .java file with the same name as the class. However it is possible to define a class within another class, thus having more than one class in a single file. This is called an inner class. We are only introducing this idea because the new version of CodingGround does not support more than one source file in an example. So in order to have multiple classes in an example, we have to use inner classes. This is a strange limitation as practically all programming languages support breaking projects into multiple source files. The old version of CodingGround allowed multiple files but may stop being supported at any time.

 

Navigation:

Overview: 
Wrap up the method unit with references to other sources of information on Java methods.
Objectives: 

View some different explorations of Java methods.

Content: 

We are going to wrap-up the unit on methods with several resources for you to view:

Here is a video about methods. This video is a good introduction to methods. However the definition of the static keyword in this video is incorrect. Please ignore the discussion of static for now as we will explore static later in this curriculum.

Here is a detailed discussion of methods. Here is another discussion (stop at "Constructors").

Navigation:

Overview: 
Explore what "overloading" is and how it is used with methods.
Objectives: 

Understand the "overloading" concept and how it applies to methods and how to use it.

Content: 

Remember that we mentioned that a method's name and parameter list are called the method's signature and this signature is how Java identifies methods. So it follows that while methods with a different name are definitely not the same method, methods with the same name and different parameter lists are also not the same method. This allows you to use different parameter lists to create variations of a method single name. This is called overloading. Here is an example of overloading:

The calling code can call square() with a double or an integer and the correct method for the parameter data type will be used. Here is an example showing varying the number of parameters:

Calling code can use either method but the second has the option to return the area in meters. Note that the second method reuses the first method so that the basic area computation is only defined in one place. In effect, the second method "adds to" or "overloads" the functionality of the first.

Here is this example in CodingGround. Add new methods to compute volume (with and without the meters option) if a height parameter is supplied. In your new methods, reuse the computeArea() method.

 

Navigation:

Overview: 
Explore how the code that calls a method can pass variables (data) to the method for the method to process.
Objectives: 

Understand passing parameters to methods from the code that calls the method and how this input makes methods much more general and useful.

Content: 

Parameters (also called arguments) are the way in which we can send data (variables or constants) to a method for it to act on. While there are cases where methods may not need parameters, parameters make methods especially useful. Parameters allow a method to produce a different result each time it is called depending on the input values supplied. Parameters are said to be "passed" to the method.

A method parameter-list consists of one or more parameters (separated by commas) specified between the method definition parenthesis. A parameter is defined by a data type and a name. The data type can be any Java data type (primitive or reference) and the name any name you wish. The name is a method local variable (placeholder) used to access the parameter's value inside the method. Here is a simple example:

Here two integer parameters will be passed to the method computeArea() when it is called. The method uses these parameters to compute the result which is returned to the calling code. Calling this method might look like this:

The variable area will contain 100. The computeArea() method can be reused to compute any area, any number of times for any height and width values passed on the call. Using a method to compute the area is also handy if the way you compute the area changes. You only have to change the method, not all the places it is called, which is what you would have to do if you had coded the area computation everywhere you needed it.

Parameter lists can contain variables or literal values. Note that variable names used on the method call do not have to match the names on the parameter list but the data types must match. In the example above, the method uses the parameter names height and width, but the calling program passed a literal value and a variable called x. At the same time, the method cannot use the variable x, it must use the variable width. In other words, I will call computeArea() with the variable x, but in the computeArea() method that value will be known as width.

In Java, primitive parameters are passed to methods by copying the parameter values from the calling code into the methods placeholder variables. This means that changing a parameter inside the method does not change that variable in the calling code. In our example, if you changed the width variable in the computeArea() method, that would not change the variable x in the calling code. This scheme is called passing parameters by value. Passing reference variables (objects) as parameters follows this same scheme but has some differences to be aware of. We will discuss this in it's own lesson in Unit 8.

Here is the example in CodingGround. Add code to the computeArea() method in the example to change the value of the width variable before the computation. Add code to the main() method to show that the variable x is unaffected by your change to width.

Using your knowledge of the switch statement, add a new method that takes an integer parameter from 1-7 that represents the day of the week and return the name of that day. Call that new method from the main() method and print out the day name.

Remember the main method from the Hello World! example? Here is the main() method definition again:

Now we can see that the main() method has a parameter list, which consists of one parameter, an array of String values. We will discuss arrays later, but for now the args parameter is a list of options (also called arguments) that are passed to the main method by the JVM when the program is started.

 

Navigation:

Overview: 
Explore how data can be returned from a method to the code that called the method.
Objectives: 

Understand returning data from a method and how this construct is used to communicate results from a method to the code that called the method.

Content: 

While methods can perform their function without returning any data to the calling code, a common use of methods is to perform some process or computation and return a result to the caller. When a method does not return a value, the return data type is called void. An example of a method that would have no return value would be a motor’s setPower(x) function. When we use that function, we aren’t looking for the code to compute something and give us the result, but we are asking the method to make some change in the robot hardware’s current running state. Void sounds like a negative connotation, but it only indicates that a method does not give us a value back. 

When we do want to return a value, the data type in front of the method name defines what kind of data we will return. The statement we use inside a method to send a data value back to the calling code is return. Return stops method execution and returns the value specified on the return statement. The data type of the value on the return statement must match the data type specified on the method definition. Here is an example:

We would call that method like  this:

This would place 2 into variable z. Note that the method does not require an input (hence the parentheses are empty). It will always return an integer value of 2. The variable x is defined inside the method so it is only visible inside the method.

We could also do this:

That would place 7 into z.

If you are returning a value, all return statements in the method must return a value of the correct data type. If the return type is void, all return statements in the method must not have a value on them.

You can return all data types including reference types (objects). Here is an example using the String data type:

We would call that method like  this:

This would print "my string" on the screen twice.

Note that a method can be called any place a data value that has the same type as the method returns. In the second println() statement, the JVM will execute the method which returns a string and then that string is passed into the println() method which can accept a string input.

When working with objects, methods can alter the internal variables of the object thus changing the object's state. This is the most common case of a method that does not return data to the caller. In this case, the result of the method's actions is the altered state of the object. This will be discussed in more detail in the unit on objects.

Here is the example in CodingGround. Add a new method that returns a double value of 22.7. Then modify the main method to call your new method and print the returned result.

A robotics example of a return value is getting information about the hardware. For example, lets say a touch sensor has a method getTouch() that returns a boolean, false if not touching anything, true if touching something. We might write this code:

Here the  sensor.getTouch() method returns a boolean, which is then tested by the if statement. A robotics example of a method with no return is controlling the behavior of a motor:

The power level is set to zero in the motor object and the method takes care of sending that power level to the actual motor on the robot.

 

Navigation:

Overview: 
Explore the structure of methods and how they are defined.
Objectives: 

Understand the structure of methods, the method header and how to write methods.

Content: 

The form of a method is:

The components are:

  • modifiers control access to methods and other special effects on methods. Modifiers will be discussed later. For now just use the word public.
  • return-type defines the data type of the method's return value if any. If there is no return value, use the word void. At a basic level, a return value is what the function will give back to us when it’s done running. We will discuss return values in the next lesson.
  • name is the name of the method. It is case sensitive.
  • parameter-list is an optional comma separated list of data values to be passed from the calling code to the method for its internal use. These are the inputs to the function, like the x in f(x). If no parameters use empty parenthesis. Parameters will be discussed shortly.
  • exception-list is a list of possible errors (called exceptions) the method might generate. We will discuss exceptions in an advanced lesson.
  • statements is one or more variable definitions or statements that make up the body of the method, and determine what the method actually does.

The name and parameter list are used by the compiler to determine which method is which and the two together are called the method signature. When called, the statements inside a method's curly braces (the method body) are executed one after another until the end of the method body is reached. You can end method execution prior to the end of  the body with the return statement.

Variables defined inside a method (called local variables) can only be accessed in that method. Global variables, that is variables defined in the class that contains the method, are accessible in the method.

Methods are called by using the method signature (name and any parameters) in a statement.

Lets look at an example (ignore the static modifier and args parameter for now):

This program will print out "Hello World! 15" two times. The JVM will start the program by calling the main() method. The main method calls myMethod() twice. myMethod() calls myMethod2() passing in the value in variable x and gets back the result of the computation in myMethod2(). That result is then stored in x in myMethod(). This is a pretty simple example but shows how the processing in the methods myMethod() and myMethod2() are easily used by calling code. As we learn more about methods we will see how useful they can be and how they are the cornerstone of object based programming.

 
Here is this example in CodingGround. Modify the example to add a new method whose name is your first name. Have that method print out Hello followed by your name.
 
 

Navigation:

Overview: 
Explore the concept of a Method, why they exist and why we need them.
Objectives: 

Understand the general concept of a Method and the use cases for Methods.

Content: 

Methods are reusable code blocks that are only executed when called from another location in your program. Methods are also called functions or subroutines. For our purposes, these names mean same thing. In other languages, the names may mean something a bit different.

In math, the parallel to a method is a function, like f(x). The function f takes in an input, x, and does something to it and optionally returns a result. Let’s say we want to square a number and then take three away from it. In math, we would write f(x) = x*x - 3. Then, we can later say f(2), and since we have defined what the function f(x) is, a reader would know that f(2) will give us 1 (4-3). This allows us to re-use a process that we may want to repeat throughout our code.

Methods help reduce complexity by taking code blocks that repeat and writing them in one place and then calling the blocks whenever we need them.

Methods streamline code by allowing us to break a complex algorithm into smaller sections of code, each easier to understand, but callable as part of the overall algorithm. That is, we can write a more complicated function by putting together smaller, simpler functions that each do a simpler step.

Methods allow objects to contain executable code (as well as data) which can be called by users of those objects. This is the basis of APIs in Java. We will ignore the object aspects of methods for the moment, looking only at method basics. For now, know that methods are defined inside Java classes and that a method cannot contain another method. In our example program Hello World, the block of code titled main is a method.

 

Navigation:

Pages