Java, A Beginners Guide - Chapter 4

advertisement
Java, A Beginner’s Guide
Fifth Edition
by Herbert Schildt
Chapter 4
This chapter covers classes, objects and methods in closer detail. Classes are the building
blocks of Java, and classes define the majority of objects in Java. Methods, as we’ve seen a little
of already, create common tasks that Java can execute
Class Fundamentals
This section covers the idea of a class in Java, which is basically the building block of all Java
code. All code in Java happens within a class of some sort, the code the book has gone over so
far occurs in a very basic class, if you recall the opening line of all the code so far started with
"class."
The General Form of a Class
The general form of a class follows, as seen on page 105 of the book.
Syntax
class classname {
type var1;
type var2;
type varN;
type method1(parameters) {
}
type method2(parameters) {
}
type methodN(parameters) {
}
}
The classname is the name of the class being defined, which generally will also be the name of
the Java file you are working on. The type for each variable (var1, var2 … varN) will be the data
type associated with that variable. These variables are class scope variables that can be
accessed and used throughout the class. The type for each method (method1, method2 …
methodN) defines the data type, if any, that will be returned from that method. If you recall from
the main() method in previous examples the void type was used, which means no data type will
be returned.
The main() method is also an optional method, it is only required when the class itself will be
executed directly and not instantiated through another class. All of the classes we've created so
far have been executed directly, so they had to have main() methods to run.
Defining a Class
This section walks through defining a simple class that is not directly executed. This class will
house three pieces of data; passengers, fuelcap and mpg. These data items are related to
vehicles, and they appropriately name the class "vehicle." See page 106 for the code used for
this class, it is fairly straightforward using 3 int variables to store the data.
Creating an Object from a Class
Classname variableName = new Classname();
Above is the general syntax for creating an object from a class, this syntax applies to built-in
classes and user defined classes. The Classname, the capitalization of the C is somewhat
significant as it is generally a best practice to start class names with a capital, is the name of the
class for which you want to create an object. The variableName is the name of the variable that
the reference to this object should be stored. The new keyword here tells Java to create a new
object from this class using the constructor, covered later. Finally you put the Classname again
with parenthesis afterwards followed by the statement terminating semicolon. There are optional
parameters that can be in the parenthesis, these are covered later with constructors.
Setting Values in a Class
object.member = value;
The general syntax for setting a value of a member of a class, or a variable inside a class, is
above. The object will be the name of the variable that you stored the object reference to when
you created the object. The member is the name of the variable you wish to manipulate. Finally
you have the value after the assignment operator. The syntax is very similar to how you assign a
value to a regular variable, with the exception of the object and member relationship. The value
must match the target data type as well, similar to variable assignments.
Page 106 through 108 in the book has an example of using the class and assignments with the
Vehicle class.
How Objects Are Created
This section covers the idea that the variable used with creating an object from the last section is
actually storing a reference to an object, not the object itself. This becomes very important with
more complicated programs and as you start making your own classes. You can store that
reference to multiple variables and they would all manipulate that same object, so you can't
simply copy the variable to another and have a new object to manipulate.
Example
Vehicle testVehicle = new Vehicle();
Vehicle testVehicle2 = testVehicle;
In the above example, testVehicle and testVehicle2 are the same object. That means that if you
alter the mpg of testVehicle2 it also alters the mpg of testVehicle, since they both reference the
exact same object.
Example
Vehicle testVehicle = new Vehicle();
Vehicle testVehicle2 = new Vehicle();
In this example, testVehicle and testVehicle2 are autonomous instances of the Vehicle class. So
if you alter the value of mpg on testVehicle2 it will not impact the mpg of testVehicle.
Reference Variables and Assignment
The notes from how objects are created went into this section, which goes over the fact that you
can copy the references between variables as seen in the first example.
Methods
This section briefly introduces methods, we have seen methods already with our main( ) method
in previous programs. Also, for reference, methods will be referred to with a set of parentheses
after them ( ) to indicate they are a method and not some other type of identifier, so main could
be a variable name where main( ) is a method.
Syntax
return-type methodName( parameter list ) {
methodBody
}
Above is the basic syntax for a method, also on page 110 of the book. The return-type is the data
type that will be returned from the method. All methods must have a return-type, but that returntype may be void if there will be no data returned. The methodName is the name of the method,
which can be anything you'd like following the identifier rules of Java (first character $, _, A-Z
ETC). The parameter list is an optional list of input parameters, if defined these must be provided
when the method is called. It is worth mentioning that you can have multiple methods with the
same name but different parameter list values; you can have one method with no parameters,
one with a String parameter, one with an int parameter ETC. The methodBody is the statement,
or set of statements, to be executed when the method is called.
Adding a Method to the Vehicle Class
This section walks you through adding a method to the Vehicle class created earlier.
The method they add is called range( ) and it simply multiplies the value of fuelcap by
the value of mpg and prints it using System.out. See page 111 for details.
Returning from a Method
This section introduces the return keyword. In this particular section it is introduced simply as a
way to exit a method at certain points, skipping any code following. You might think of the return
keyword, in the method context, similar to the continue or break keywords for loop probably more
similar to break. If your method has a void return type, you can use return at any point to exit the
method.
Syntax
return;
Returning a Value
The return keyword can also return a value, and is required if your method has a return type other
than void. Also, the value returned must match that return type's data type. You are allowed to
use literal values as well as variable of the proper data type.
Syntax
return value;
To return a value, you simple add the value after the return keyword as part of the statement.
The value must match the return data type, and it can be a variable name as well. Page 114 and
115 have some examples of returning a value.
Using Parameters
This section covers using parameters with methods. If you define a method with a parameter list,
or call a method that requires parameters, you pass the parameters when you call the method.
With the example methods so far, you simple called the method by using methodName( ). The
parentheses are empty in the method calls so far since there are no parameters. If your method
requires parameters, you simply add them between the parentheses, in order and separated by
commas.
Syntax
methodName(parameter1, parameter2, …, parameterN);
The methodName will be the name of the method you are calling. In between the parentheses
you will notice parameter1 through parameterN, indicating there may be any number of
parameters. Java does not name the parameters when calling a method, there are some
languages where you may specify the name of the parameter you are passing. In Java, you must
pass the parameters in the appropriate order, which is the order they are defined in the code.
Also, these parameters must match the data type specified by the method. You may pass literal
values or variables containing the values in the appropriate data type.
Adding a Parameterized Method to Vehicle
In this section you learn how to create a method that accepts, or requires, parameters. The
general syntax is included in the methods section of the notes. By defining the parameter list
your method will require parameters.
Syntax
dataType1 parameterName1, dataType2 parameterType2, …, dataTypeN
parameterTypeN
The above syntax is for the parameter list portion of the method syntax in the methods section.
We have dataType1 and parameterType1 through dataTypeN and parameterTypeN, indicating
there may be any number of parameters. The dataType is any valid Java data type, including
classes. The parameterName is the name of the parameter inside of the method, this is how you
will refer to that value. The parameterName can be any valid Java identifier.
See page 117 and 118 for examples.
Creating a Help Class
This section covers the example application for this chapter, it takes the help program from
Chapter 3 and converts it into multiple classes and methods.
Constructors
Constructors are used to create objects out of classes. Java will automatically generate a bare
constructor if you do not explicitly define one in your class.
Syntax
Classname (parameter list) {
// Constructor body
}
Above is the general syntax for a constructor. You might notice it is very similar to a method, but
the name must match the class name and there is no return type. Everything else is practically
the same for a constructor. You can specify any number of parameters and put as much code as
you like inside of its body. Note that the constructor will be used by the new keyword when
creating objects.
See page 125 for examples.
Parameterized Constructors
This section adds the parameter list to the constructor, the notes on the previous section cover
this possibility. Adding parameters will require a slight modification of your new statement when
creating objects, similar to how you call methods with parameters.
Syntax
Classname objectName = new Classname(parameter1, parameter2, …, parameterN);
Above is the general syntax for creating an object from a class with a parameterized constructor.
The Classname will be the name of the class you are creating an object from. The objectName is
an identifier that the reference will be stored to, or variable. Then the parameter1 through
parameterN, indicating any number of parameters, contain the parameters for the constructor.
These must be in order and of the proper data type; literals, variables or other derived values are
valid.
Adding a Constructor to the Vehicle Class
This section goes through adding a constructor to the vehicle class created earlier in the chapter.
In this case, the book created a constructor with three int type parameters to populate the values
of passengers, fuelcap and mpg.
See page 127 for examples.
The new Operator Revisited
This section recaps the new operator in full syntax, similar to the syntax in the parameterized
class section of the notes.
Garbage Collection and Finalizers
As you create objects in Java they are created and stored in dynamically allocated memory.
Unfortunately, memory is a finite resource so it is possible that Java may eventually run out of
memory and not be able to create or process further objects. To combat this, Java keeps track of
objects and if they will be further used or if they are no longer usable, out of scope. Java will run
garbage collection at random times, it takes resources to run garbage collection so you don’t
want it running during a heavy portion of your application. When garbage collection is run, Java
finds the objects that are no longer used or useful and frees that memory. When the object is
freed from memory, there is a finalize( ) method that will be run on that object, if you need special
things to happen before the object is removed you would define this method and put the
instructions in there.
The finalize( ) Method
As introduced in the previous section, the finalize( ) method is called when Java garbage
collection frees and object from memory.
Syntax
protected void finalize( ) {
// finalization body
}
Above is the general syntax for the finalize( ) method, the only thing you would really change is
the finalization body. In the finalization body you can put the code in to close flies, finish work or
any other thing you need Java to do before that object disappears.
Demonstrate Garbage Collection
As stated in the garbage collection section, the garbage collection process is essentially random.
This section demonstrates some code to try to force garbage collection to happen and make the
process “visual” by putting a System.out.println in the finalize( ) method, which would print text to
the screen when garbage collection runs.
The this Keyword
The this keyword is used to force a reference of an identifier to the current instance of an object
or class. It is possible to have a parameter list of a method contain identifiers that match the
names of identifiers for a class. For instance, the Vehicle class has identifiers named
passengers, fuelcap and mpg. You could have a method within Vehicle that also has parameters
named passengers, fuelcap and mpg. If you do, it would be hard to interact with the class
identifiers with these names, but if you prefix the identifier name with this, it will explicitly
reference the class identifier.
Syntax
this.identifier
Above is the general syntax of the this keyword. The identifier will be the identifier you reference.
Example
void setMPG(int mpg) {
this.mpg = mpg;
}
The above example creates a method called setMPG( ) which takes an int parameter called mpg.
The method then sets the object identifier named mpg, referenced by this.mpg, to the value of
mpg passed to the method. The above example is the most common use of the this keyword I
have seen.
Download