Chapter 4 Defining Classes I This chapter introduces the idea that students can create their own classes and therefore their own objects. Introduced is the idea of methods and instance variables as the two components of classes. With the introduction of methods, we can discuss parameters and parameter passing. Encapsulation is then introduced with the designation of accessor and mutator methods. Then, the concept of method overloading is introduced. Constructors are given coverage in the last section of this chapter. KEY TERMS Object call-by-value private Method parameters as local variables accessor method, Instance formal parameter mutator method Member actual parameter precondition Field this parameter postcondition instance variable mask a variable overloading New equals method signature Heading tostring constructor method body println used with objects constructor arguments Invocation + used with objects resetting object values Body recursive method no-argument constructor return statement driver program default constructor return in a void method bottom-up testing import local variable stub tokens Block information hiding nexttoken compound statement abstraction hasmoretokens Parameter encapsulation, choosing delimiters Argument public
4.1 CLASS DEFINITIONS Instance Variables and Methods More about Methods Local Variables Blocks Parameters of a Primitive Type Simple Cases with Class Parameters The this Parameter Methods that Return a Boolean Value The Methods equals and tostring Recursive Methods 4.3 OVERLOADING Rules for Overloading CHAPTER OUTLINE 4.2 INFORMATION HIDING AND ENCAPSULATION public and private Modifiers Accessor and Mutator Methods Preconditions and Postconditions 4.4 CONSTRUCTORS Constructor Definitions Default Variable Initializations An Alternative Way to Initialize Instance Variables The StringTokenizer Class Key Points A Class is a Type The notion of the difference between a class and an instance comes up again in this chapter. Also, students need to be made aware that you can create a variable whose value will be an object. The type of the variable will be the class. The new Operator The new operator is what is used to actually create an instance. You would use the new operator when you are assigning a value to a variable whose type is a class. Class Definition A class definition begins with the keywords public class followed by the name of the class. The definition of the class is enclosed between {} and usually the instance variables for a class are listed before the methods. This is by convention and not compiler enforced. Normally, all the instance variables are placed at the top of the file. File Names and Locations In java, each file should contain one class and the name of the class and the file will be the same. For now, all files for the same project should be in the same directory. There are other ways to organize files, namely into packages, but the text has not introduced this idea yet. return Statements When writing a method that has a return type that is other than void, a return statement needs to be in the method. If omitted, this will cause a compiler error. A void method does not need a return statement. Method Definitions The first part of a method definition is the method signature, which consists of its visibility, which is usually public, its return type, the method name and the parenthesized list of parameters. Methods are first introduced where they do not take any parameters. The method body is enclosed in {} and if the return type of a method is other than void, a return statement must be included in the list of statements for the method.
Local Variables You can have instance variables that are accessible to the entire class. You can also create variables inside a method that are only accessible within that method. With these variables, you do not need to give them a visibility, just a type and a name. You can then use these variables in any computation within the method. Global Variables This type of variable in not available in Java. Blocks The notion of blocks of code encompasses the idea that code enclosed in {} is considered a block. This can be the {} around a loop body or within an if-else statement. However, for purposes of local variables, they are only accessible from within the block, but their names cannot be repeated within the method. Parameters of a Primitive Type Parameters into a method can be of a primitive type. When primitive values are passed into a method, the value of the parameter is initialized to the value that is passed in from the method call. This method is call-by-value parameter passing and unlike other languages, is the only type of parameter passing that Java supports for primitive types. You can also pass in parameters whose type is a class. These parameters are handled by Java differently and will be discussed in the next chapter. main is a void Method. If you look at the method signature of the main method, you will see that its return type is void. It also takes a parameter named args. We will discuss static and the type of thing that the parameter is (an array) in later chapters. The this Parameter. There is a keyword in Java whose meaning is to refer to the class itself. The keyword this is used whenever you want to refer to the class. You can use the keyword this as a calling object for methods within the same class. We will see using this as a parameter when we talk about passing objects as parameters. The Methods equals and tostring. It is good practice when writing Java classes that you write an equals and a tostring method. The equals method can help determine whether two objects are equal and returns a Boolean value. The tostring method returns a String representation of an object. The Fundamental Rule for Testing Methods When testing a new method, it should be maintained that all of the other methods being called in the testing program have already been tested and debugged. Encapsulation The idea of encapsulation is that all of the data and the actions that can be performed are combined in one place (class). If a class is well designed, the user of the class only needs to be told what the class is capable of, not the specific details of how it is implemented. API The Application Programmer Interface is used to tell users of the class what the class can do. There is an online Java API that is available for all of the classes inside Java. ADT Abstract Data Types are written using information hiding techniques. Signature The signature of the method consists of its visibility, return type, method name, and parameter list. This term can also be introduced right when methods are first introduced in the text. Overloading Java supports method overloading. Two methods can have the same name if they differ in number and or type of parameters.
You Cannot Overload Operators in Java Unlike other languages, Java does not provide the ability to overload operators. Constructor The constructor is a special method that is in charge of setting up the initial state of an object. It is executed when an object is created using the keyword new. Is a Constructor Really a Method? A constructor does not follow the same signature as other methods (no return type) and it is not called in the same manner. Tips Any Method Can Be Used as a void Method. This tip points out the fact that if the return value from a method is not placed into a variable, the value is essentially lost. This could be a positive for a program in that we can ignore a value that is returned if we do not need it. Declaring Variables in a for Statement In a for statement, the first part is an initialization, commonly seen as int n = value. However, when the variable n is declared in the for loop, it is not accessible outside of the loop. To avoid this problem, we must declare the variable outside of the loop and only initialize it in the loop. This feature of when variables can be accessed can be both a pitfall and a help depending on when the variable needs to be accessed. Testing Methods Each method of a class should be tested. One of the easiest and best ways to do this is to create a driver class that creates an instance of the object and tests each method in turn. Care needs to be taken when testing methods that call other methods so that it is assured that all methods are working properly. A Class has Access to private Members of All Objects of the Class When an entity is declared private the only elements that have access to it are other entities inside that same class. This is the most restrictive visibility. Mutator Methods Can Return a Boolean Value An alternative implementation for a mutator method is to have the method return a boolean value that indicates whether the changes requested by the caller were successful. You Can Invoke Another Method in a Constructor You can make a call to another method from the constructor by simply using the same technique as we have used to call methods previously. Include a No-Argument Constructor. If you do not provide a constructor for a class, Java provides one for you that takes no arguments. It is a good idea to include a no-arg constructor that does something meaningful so that the default constructor that does nothing will not be called. You lose the default no-arg constructor as soon as there is at least one constructor defined in the class, so having another that takes no parameters is a good programming practice. Pitfalls Use of the Terms Parameter and Argument The use of these two terms varies from author to author and it should be well known which context the words are used in. For this text, parameter is used to describe the formal parameter or the name of the parameter in the method signature. The word argument is used to describe the actual parameter or the actual value that is passed into the method when it is called.
Overloading and Automatic Type Conversion When a method is called in Java, it looks to match the method signature. If it fails to match the signature exactly, Java will try to do a conversion to match. For example, it may convert an int into a double to match for a signature. This has the potential to cause problems within a program. You Cannot Overload Based on the Type Returned A method can not be overloaded based on the return type of the method. Overloading is only concerned with the parameters for a method, not the return types.