Java 1400 - Exam 3 Study Guide (Lectures 15 - 19)

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

Class Scope Accessors

Accessors This is accessible by the instance variables and methods that they can be accessed anywhere in the class.

3 Java class members

Members Instance variables, class variables, and methods.

Method body parts

Parts In this part of a method, a method can declare variables, call other methods, and use any of the program structures we've discussed: if/else statements, while loops, for loops, switch statements, and do/while loops. All objects of a class share one copy of the class methods.

Scope Rules

Rules A method in a class can access • the instance variables of its class • any parameters sent to the method • any variable the method declares within its body from the point of declaration until the end of the method or until the end of the block in which the variable was declared, whichever comes first • any methods in the class Note: Attempting to use an identifier that is not in scope will generate the following compiler error: cannot find symbol

Public Vs. Private Declaring rules

Rules Classes, constructors, final class variables, and class methods typically are declared as public Instance variables typically are declared as private.

Constructor Rules

Rules If we don't provide this, the compiler provides a default one of these, which is a one of these that takes no arguments. This default one of these assigns default initial values to all the instance variables. Numeric variables are given the value of 0, characters are given the value of the Unicode null character, boolean variables are given the value of false, and object references are given the value of null.

Variable Rules

Rules One copy of each instance variable is created for every object instantiated from the class. One copy of each class variable and method is shared by all objects of the class.

Instance Variables rules

Rules These are nouns and begin with a lowercase letter; internal words begin with a capital letter, and all other letters are lowercase. Each instance variable and class variable must be given a name that is unique to the class. It is legal to use the same names for instance variables in different classes, but within a class, the same name cannot be used for more than one instance variable or class variable. Thus, we say that the fields of a class have class scope. Optionally, you can declare an instance variable to be a constant (final).

Method names rules

Rules These are verbs and begin with a lowercase letter; internal words begin with a capital letter, and all other letters are lowercase.

Field Variable rules

Rules These constants have all capital letters with internal words separated by an underscore. These are also known by several names: Global variables, Instance variables, Class variables, Data members, characteristics, or attributes. Just remember, what ever they are called, they are accessible across multiple methods. This is declared in a class Example - ""total"" is one of these public double total; public void withdraw( double amount ) { total -= amount; }

Accessor Methods (Getters) Rules

Rules These methods are named getIV, where IV is an instance variable name; the return data type is the same as the instance variable, and the body of the method simply returns the value of the instance variable.

Mutator Methods (Setters) Rules

Rules These methods are named setIV, where IV is an instance variable name; the return data type is void or a reference to this object, and the method takes one argument, which is the same data type as the instance variable and contains the new value for the instance variable. The body of this method should validate the new value and, if the new value is valid, assign the new value to the instance variable.

Static class methods Rules

Rules These methods can reference only static variables, can call only static methods, and cannot use the object reference this. A non-static method does not have the keyword static before the name of the method. A non-static method belongs to an object of the class and you have to create an instance of the class to access it. Non-static methods can access any static method and any static variable without creating an instance of the class.

Package Access Rules

Rules This allows other classes in the same package or folder to access the class or class members.

Default Constructor Rules

Rules This assigns default initial values to all the instance variables. This type of thing takes no arguments (has nothing in the parenthesis (). If you don't write one of these in the coding, the compiler will provide one. This will assign default initial values to all instance variables (this is called auto initialization).

Void Rule

Rules This does not return a value in a method. Only used in setters or static methods. Not used it getters (because they return a value in their body)

Local Variables Rules

Rules This is declared in a method These are accessible only inside the method it was declared in Example: ""amount"" is one of these public void deposit ( double amount ) { total += amount; }

Method Body Rule

Rules This is enclosed in curly braces which defines the scope area of a method. The code will go inside of here which will either return a value, test a value (if statement), bring in a value to use in an instance of an object, and many other possible uses.

Instance Method (non Static) Rules

Rules This method can reference both class and instance variables, as well as class and instance methods, and the reference this.

.equals Method Rule

Rules This method compares two objects for equality; that is, it should return true only if the corresponding instance variables in both objects are equal in value, and false otherwise.

toString Method Rule

Rules This method is called automatically when an object reference is used as a String, and its job is to provide a printable representation of the object data.

Access Modifiers Chart

Chart Access Modifier Class or Member can Be Referenced by ... public methods of the same class, as well as methods of other classes private methods of the same class only protected methods in the same class, as well as methods of subclasses and methods in classes in the same package no modifier methods in the same package or same folder only (package access)

Default Constructor initial values of Instance Variables Chart

Chart Data Type Initial Value byte 0 short 0 int 0 long 0 float 0.0 double 0.0 char null character ('\u0000') boolean false object reference null

instance of syntax chart

Chart Operator Syntax Operation instanceof objectReferenceinstanceof ClassName evaluates to true if objectReference is of ClassName type; false otherwise

Instance variables Defining

Defining Define these for the data that all objects will have in common. For example, for a Student class, you might select the student name, grade point average, and projected graduation date. For a Calculator class, you might select two operands, an operator, and a result. { private String model; private int milesDriven; private double gallonsOfGas;}

Method Overload Definition

Definition Multiple methods may have the same name as long as they have different parameter lists. The parameter list must differ in on of 3 ways: • Data type • Number of parameters • Order of parameters So, this can be used here by defining another method with the same name but a different signature; that is, with a different number of parameters or with parameters of different data types. For example, when When we provide multiple constructors, we are overloading a method. To do this in a method, we provide a method with the same name but with a different number of parameters, or with the same number of parameters but with at least one parameter having a different data type and a different signature. (Note: the return type is not part of the signature)

Class Definition

Definition These encapsulate the data and functionality for a person, place, or thing, or more generally, an object. For example, a this might be defined to represent a student, a college, or a course.

Accessor Methods (Getters) Definition

Definition These methods take no arguments and simply return the current value of the instance variable. This is needed because clients cannot directly access private instance variables of a class, so these methods are needed to return them. This return type is the same data type as the instance variable. Using these simple method patterns, you should provide public accessor methods for any instance variable for which the client should be able to retrieve the value. Each of these returns the current value of the corresponding instance variable.

Instance variable Naming Vs Parameter name Error

Error A common error in writing mutator methods is using the instance variable name for the parameter name. When a method parameter has the same name as an instance variable, the parameter hides the instance variable. In other words, the parameter has name precedence, so any reference to that name refers to the parameter, not to the instance variable. For example, the intention in this incorrectly coded method is to set a new value for the model instance variable: // Incorrect! parameter hides instance variable public void setModel( String model ) { model = model; } Because the parameter, model, has the same identifier as the model instance variable, the result of this method is to assign the value of the parameter to the parameter! This is called a No-op, which stands for "No operation," because the statement has no effect. To avoid this logic error, we can choose a different name for the parameter. To avoid name conflicts, we name each parameter using the pattern new Instance Variable. A similar common error is to declare a local variable with the same name as the instance variable, as shown in the following incorrectly coded method: // Incorrect! declared local variable hides instance variable public void setModel( String newModel ) { String model; // declared variable hides instance variable model = newModel; }

Instance Variables Definition

Definition These variables reflect the properties that all objects will have in common. Each object, or instance of a class, gets its own copy of the instance variables, each of which can be given a value appropriate to that object. They are defined by specifying an access modifier, data type, identifier, and, optionally, an initial value. These variables can be declared to be final. They are defined by specifying an access modifier, data type, identifier and could include an optional initial value These variables have class scope which means they can be accessed anywhere in the class **Syntax: accessModifier dataType identifierList;

Method Argument Definition

Definition This are what we pass as input to methods. Once we have created this, we will use a methods parameters to store the value from this into another variable. It doesn't have to be the same variable name and the parameters variable. These aren't just restricted to variables, this can be any integer value. You can use as many of these as you like. If you use more than one of these (multiple) in a class, they can be used to perform many things like math or comparisons. Just make sure if you are using more than 1 in a class, you must use the same amount of parameters also. Make sure you use commas to separate the parameters in a method when calling them out.

Method Definition

Definition This is a small, self-contained unit of code that accomplishes a singular, well-defined task. This can reference the instance variables of its class, the parameters sent to the method, and local variables declared by the method, and it can call other methods of its class. These separate well defined tasks in your program into different blocks of code In order to use one of these, you must perform a ""method call"" by writing the method name followed by parenthesis and a semicolon. Reasons for using these: • Organizes code • Avoids code repetition • Easier to debug and maintain code

Constructors Definition

Definition This is a special method that is called when an object is initialized using the new keyword. It should always be the first method in a class. Whenever you create an object, that class's constructor will be called which WILL ALWAYS BE public. It creates an instance of the class, which is an object. A class can have several of these. The job of these is to initialize the variables and fields of the new object. In other words, these are responsible for initializing the instance variables of the class. The arguments that we pass to constructors will be the values that the global variables will be initialized to. It has the same name as the class and has no return type (does not use void either). They must use the public access modifier so that the applications can instantiate objects of the class.

Parameter List Definition

Definition This is always located at the end of a method header. It is used to define input if we need it. If we are not needing to define anything, we leave the inside of these parenthesis blank. *Syntax of a method header access_modifier return_type method_name (parameter_list) { code return_statement (if applicable) }

Scope Definition

Definition This is defined as ""where a variable is accessible in code"" or when a method can access its parameters directly because the parameters can be accessed only in that method; that is, a method can access its own parameters This is defined as ""where a variable is accessible in code"" or when a method can access its parameters directly because the parameters can be accessed only in that method; That is, a method can access its own parameters and are accessible from the point of definition until the end of the method or the end of the block in which the variable was defined, whichever comes first. This block of codes boundaries are determined by a set of curly braces, or a control structure. are accessible from the point of definition until the end of the method or the end of the block in which the variable was defined, whichever comes first. This block of codes boundaries are determined by a set of curly braces, or a control structure.

Method structure Definition

Definition This is defined by providing a method header, which specifies the access modifier, a return type, the method name, and a parameter list. The method body is enclosed in curly braces. Value-returning methods return the result of the method using one or more return statements. A method with a void return type does not return a value.

Methods signature Definition

Definition This is the name of the method, along with the number, data types, and order of its parameters

Object Reference This Definition

Definition This is used in methods where you need to avoid ambiguity in variable names, you can precede an instance variable name with this. That approach comes in handy as a way to avoid one of the common errors we discussed earlier in the chapter: A parameter of a mutator method with the same name as the instance variable hides the instance variable. We can eliminate this problem by using the this reference with the instance variable, which effectively uncovers the instance variable name.

toString Method Definition

Definition This method is called automatically when an object reference is used as a String. For example, this method for an object is called when the object reference is used with, or as, a parameter to System.out.println. The function of this method is to return a printable representation of the object data. In other words, It is used to print the information you want from the object such as the instance variable information

Data Manipulation Methods Definition

Definition This method is done to formulate the data, and also to provide some service. You would provide one or more methods that perform the functionality of the class. These methods might calculate a value based on the instance variables and/or parameters, or manipulate the instance variables in some way. The API of these methods depends on the function being performed. If a method merely manipulates the instance variables, it requires no parameters because instance variables are accessible from any method and, therefore, are in scope. For example, in our Auto class, part of the functionality of our class is to calculate miles per gallon and the gas cost, so we provide the milesPerGallon and moneySpentOnGas methods in our Auto class

Mutator Methods (Setters) Definition

Definition This method is used to declare the instance variables as private to encapsulate the data of the class. We allow only the class methods to directly set the values of the instance variables. Thus, it is customary to provide a public mutator method for any instance variable that the client will be able to change. Because the method names usually start with "set," mutator methods are often called setters. These methods are declared as public so that client programs can use the methods to change the values of the instance variables. Note: There is NO RETURN Values, so we MUST declare the return type as ""VOID"". In the body of this method, you will need to set parameters to validate the parameter entered in by the client (ie. if ( newMilesDriven >= 0 ) milesDriven = newMilesDriven;). If the entered values do not meet the required parameter specified, the default values are used instead of the users input, or you may use additional parameters with setting values if it is needed in your coding to make the instance variable a new value under different conditions.

.equals Method Definition

Definition This method takes an Object reference parameter that is expected to be an Auto reference and returns true if the values of its fields are equal to the values of the fields of this Auto object, false otherwise. This method compares two objects for the same state equality The result of this should return a "true" Boolean only if the corresponding instance variable in both objects are equal in value, otherwise the result is "false" Note: equals() method and == are not the same

Access Modifier Definition

Definition This modifier specifies where the class or member can be used. They are either public, private, protected, or have no modifier at all. Typically this in a class will by public, where we know that a public class must be stored in a file named ClassName.java where ClassName is the name of the class.

instanceof Operator Definition

Definition This operator is used to test whether the object is an instance of the specified type (class or subclass or interface). This operator in java is also known as type comparison operator because it compares the instance with type. It returns either true or false.

Return Statement Definition

Definition This part of a method body is used ONLY when we are using a ""Getter"" (Accessor) method. If you are using a ""Void"" method, you DO NOT USE this. Its used to define output if we need it. It is for accessing a value of the called instance variable in an accessor method then spitting out the value if called upon. *Syntax of a method header access_modifier return_type method_name (parameter_list) { code return_statement (if applicable) }

Return type Definition

Definition This returns the value calculated back to where the method was called from. In other words, the method call pow(base, exp) calculated an integer value. The integer value can be stored into a variable. This type is asking the question, "What is the data type of which you are calculating?" If we are not calculating a number or other data, we simply use the key word "void" in the method header. This is the 2nd part of the method header Ex. public static void Auto( ) *Syntax of a method header access_modifier return_type method_name (parameter_list) { code return_statement (if applicable) }

Static Methods Definition

Definition This unique type of method is created when you need to allow ALL OF THE objects to be able to access this unique class variable inside the class itself. Since each object created has its own uniques instance variables, these types of methods do not have access to any instance variables inside the objects. The instructor created an example method to track every time an auto was created. And since there were 3 different constructors creating the objects, this method was used to count each time one of them was used. You cant have access to the static variable used, but you can use a getter to go retrieve it for you. These contain the word ""static"" in the header and call upon a static variable that was created in the class (under the instance variable location in the class) Setter method Example: private static void updateCount() { countAutos ++; } Getter method Example: public static int getCount() { return countAutos; }

Override Definition

Definition This will allow you to provide a new version of the method to bypass the original method that is automatically inherited into a class once it is created. Due to the fact that these inherited versions may not provide functionality to our code. It is good coding practice to place the @Override annotation before the method header. It will tell the compiler that the method that follows is overriding a method inherited from another class. And in turn, the compiler warns us if our method header does not in fact override the inherited method. (ie. toString: returns a String of instance variable values) 104 @Override 105 public String toString( ) 106 { 107 DecimalFormat gallonsFormat = new DecimalFormat( 0.00"" ); 108 return ""Model: "" + model 109 + ""; miles driven: "" + milesDriven 110 + ""; gallons of gas: "" 111 + gallonsFormat.format( gallonsOfGas ); 112 }

Method Name Definition

Definition Use verbs when naming these. Begin the method name with a lowercase letter and begin internal words with a capital letter (this is known as the ""camelCasing"" convention. Ex. milesDriven or gallonsOfGas. The method header syntax should be familiar because we've seen the API for many class methods. One difference is just a matter of semantics. The method caller sends arguments, or actual parameters, to the method; the method refers to these arguments as its formal parameters. Because methods provide a function for the class, typically method names are verbs. Like instance variables, the method name should begin with a lowercase letter, with internal words beginning with a capital letter. The access modifier for methods that provide services to the client will be public. Methods that provide services only to other methods of the class are typically declared to be private.

Data hiding Definition

Definition When we write a class, we will make known the public method names and their APIs so that a client program will know how to instantiate objects and call the methods of the class. We will not publish the implementation (or code) of the class, however. In other words, we will publish the APIs of the methods, but not the method bodies. A client program can use the class without knowing how the class is implemented, and we, as class authors, can change the implementation of the methods as long as we don't change the interface, or APIs.

Method parameter naming Error

Error Be aware that a method parameter or local variable that has the same name as an instance variable hides the instance variable. Any variable that a method declares is a local variable because its scope is local to the method. Thus, the declared variable, model, is a local variable to the setModel method. With the preceding code, the model local variable hides the instance variable with the same name, so the method assigns the parameter value to the local variable, not to the instance variable. The result is that the value of the model instance variable is unchanged.

Parameter naming Error

Error Do not declare the parameters of a method inside the method body. When the method begins executing, the parameters exist and have been assigned the values set by the client in the method call. The instance variable, model, is defined already in the class. Thus, the method should simply assign the parameter value to the instance variable without attempting to declare the instance variable (again) in the method. Finally, another common error is declaring the parameter, as shown below: // Incorrect! Declaring the parameter; parameters are declared already public void setModel( String newModel ) { String newModel; // local variable has same name as parameter model = newModel; } This code generates this compiler error: variable newModel is already defined in method setModel(String)

Scope Good Example

Example 1. public static void main( String args[] ) 2. { 3. int bar = 0; 4. foo(bar); 5. System.out.println( ""bar: "" + bar ); 6. } 7. public static void foo ( int bar ) 8. { 9. bar++; 10. System.out.println( ""foo: "" + bar); 11. } Output: foo: 1 bar: 0

Scope Failure Example

Example 1. public static void main( String[] args ) 2. { 3. for ( int i = 1; i <= 3; i++ ) 4. { 5. int x = i * 5; 6. } 7. System.out.printf(""The values of x and i are: %d, %d\n"", x, i); 8. } Compilation error (line7): x and i are not defined

.equals Method Example

Example 114 // equals: returns true if fields of parameter object 115 // are equal to fields in this object 116 @Override 117 public boolean equals( Object o ) 118 { 119 if ( ! ( o instanceof Auto ) ) 120 return false; 121 else 122 { 123 Auto objAuto = ( Auto ) o; 124 if ( model.equals( objAuto.model ) 125 && milesDriven == objAuto.milesDriven 126 && Math.abs( gallonsOfGas - objAuto.gallonsOfGas ) 127 < 0.0001 ) 128 return true; 129 else 130 return false; 131 } 132 }

Accessor Methods (Getters) Example

Example 5 public class Auto 6 { 7 // instance variables 8 private String model; // model of auto 9 private int milesDriven; // number of miles driven 10 private double gallonsOfGas; // number of gallons of gas 11 12 // Default constructor: 13 // initializes model to ""unknown""; 14 // milesDriven is autoinitialized to 0 15 // and gallonsOfGas to 0.0 16 public Auto( ) 17 { 18 model = ""unknown""; 19 } 20 21 // Overloaded constructor: 22 // allows client to set beginning values for 23 // model, milesDriven, and gallonsOfGas. 24 public Auto( String startModel, 25 int startMilesDriven, 26 double startGallonsOfGas ) 27 { 28 model = startModel; 29 30 // validate startMilesDriven parameter 31 if ( startMilesDriven >= 0 ) 32 milesDriven = startMilesDriven; 33 34 // validate startGallonsOfGas parameter 35 if ( startGallonsOfGas >= 0.0 ) 36 gallonsOfGas = startGallonsOfGas; 37 } 38 39 // Accessor method: 40 // returns current value of model 41 public String getModel( ) 42 { 43 return model; 44 } 45 46 // Accessor method: 47 // returns current value of milesDriven 48 public int getMilesDriven( ) 49 { 50 return milesDriven; 51 } 52 53 // Accessor method: 54 // returns current value of gallonsOfGas 55 public double getGallonsOfGas( ) 56 { 57 return gallonsOfGas; 58 } 59 }

Auto class Example

Example 5 public class Auto 6 { 7 // instance variables 8 private String model; // model of auto 9 private int milesDriven; // number of miles driven 10 private double gallonsOfGas; // number of gallons of gas 11 12 // Default constructor: 13 // initializes model to ""unknown""; 14 // milesDriven is autoinitialized to 0 15 // and gallonsOfGas to 0.0 16 public Auto( ) 17 { 18 model = ""unknown""; 19 } 20 21 // Overloaded constructor: 22 // allows client to set beginning values for 23 // model, milesDriven, and gallonsOfGas. 24 public Auto( String startModel, 25 int startMilesDriven, 26 double startGallonsOfGas ) 27 { 28 model = startModel; 29 30 // validate startMilesDriven parameter 31 if ( startMilesDriven >= 0 ) 32 milesDriven = startMilesDriven; 33 34 // validate startGallonsOfGas parameter 35 if ( startGallonsOfGas >= 0.0 ) 36 gallonsOfGas = startGallonsOfGas; 37 } 38 }

Data Manipulation Methods Example

Example 5 public class Auto 6 { 7 // instance variables 8 private String model; // model of auto 9 private int milesDriven; // number of miles driven 10 private double gallonsOfGas; // number of gallons of gas 11 12 // Default constructor: 13 // initializes model to ""unknown""; 14 // milesDriven is autoinitialized to 0 15 // and gallonsOfGas to 0.0 16 public Auto( ) 17 { 18 model = ""unknown""; 19 } 20 21 // Overloaded constructor: 22 // allows client to set beginning values for 23 // model, milesDriven, and gallonsOfGas. 24 public Auto( String startModel, 25 int startMilesDriven, 26 double startGallonsOfGas ) 27 { 28 model = startModel; 29 setMilesDriven( startMilesDriven ); 30 setGallonsOfGas( startGallonsOfGas ); 31 } 32 33 // Accessor method: 34 // returns current value of model 35 public String getModel( ) 36 { 37 return model; 38 } 39 40 // Accessor method: 41 // returns current value of milesDriven 42 public int getMilesDriven( ) 43 { 44 return milesDriven; 45 } 46 47 // Accessor method: 48 // returns current value of gallonsOfGas 49 public double getGallonsOfGas( ) 50 { 51 return gallonsOfGas; 52 } 53 54 // Mutator method: 55 // allows client to set model 56 public void setModel( String newModel ) 57 { 58 model = newModel; 59 } 60 61 // Mutator method: 62 // allows client to set value of milesDriven; 63 // if new value is not less than 0 64 public void setMilesDriven( int newMilesDriven ) 65 { 66 if ( newMilesDriven >= 0 ) 67 milesDriven = newMilesDriven; 68 } 69 70 // Mutator method: 71 // allows client to set value of gallonsOfGas; 72 // if new value is not less than 0.0 73 public void setGallonsOfGas( double newGallonsOfGas ) 74 { 75 if ( newGallonsOfGas >= 0.0 ) 76 gallonsOfGas = newGallonsOfGas; 77 } 78 79 // Calculates miles per gallon. 80 // if no gallons of gas have been used, returns 0.0; 81 // otherwise, returns miles per gallon 82 // as milesDriven / gallonsOfGas 83 public double milesPerGallon( ) 84 { 85 if ( gallonsOfGas >= 0.0001 ) 86 return milesDriven / gallonsOfGas; 87 else 88 return 0.0; 89 } 90 91 // Calculates money spent on gas. 92 // returns price per gallon times gallons of gas 93 public double moneySpentOnGas( double pricePerGallon ) 94 { 95 return pricePerGallon * gallonsOfGas; 96 } 97 }

Mutator Methods (Setters) Example

Example 5 public class Auto 6 { 7 // instance variables 8 private String model; // model of auto 9 private int milesDriven; // number of miles driven 10 private double gallonsOfGas; // number of gallons of gas 11 12 // Default constructor: 13 // initializes model to ""unknown""; 14 // milesDriven is autoinitialized to 0 15 // and gallonsOfGas to 0.0 16 public Auto( ) 17 { 18 model = ""unknown""; 19 } 20 21 // Overloaded constructor: 22 // allows client to set beginning values for 23 // model, milesDriven, and gallonsOfGas. 24 public Auto( String startModel, 25 int startMilesDriven, 26 double startGallonsOfGas ) 27 { 28 model = startModel; 29 setMilesDriven( startMilesDriven ); 30 setGallonsOfGas( startGallonsOfGas ); 31 } 32 33 // Accessor method: 34 // returns current value of model 35 public String getModel( ) 36 { 37 return model; 38 } 39 40 // Accessor method: 41 // returns current value of milesDriven 42 public int getMilesDriven( ) 43 { 44 return milesDriven; 45 } 46 47 // Accessor method: 48 // returns current value of gallonsOfGas 49 public double getGallonsOfGas( ) 50 { 51 return gallonsOfGas; 52 } 53 54 // Mutator method: 55 // allows client to set model 56 public void setModel( String newModel ) 57 { 58 model = newModel; 59 } 60 61 // Mutator method: 62 // allows client to set value of milesDriven; 63 // if new value is not less than 0 64 public void setMilesDriven( int newMilesDriven ) 65 { 66 if ( newMilesDriven >= 0 ) 67 milesDriven = newMilesDriven; 68 } 69 70 // Mutator method: 71 // allows client to set value of gallonsOfGas; 72 // if new value is not less than 0.0 73 public void setGallonsOfGas( double newGallonsOfGas ) 74 { 75 if ( newGallonsOfGas >= 0.0 ) 76 gallonsOfGas = newGallonsOfGas; 77 } 78 }

Auto Driver Example

Example 5 public class AutoClient 6 { 7 public static void main( String [ ] args ) 8 { 9 Auto suv = new Auto( ""Trailblazer"", 7000, 437.5 ); 10 11 // print initial values of instance variables 12 System.out.println( ""suv: model is "" + suv.getModel( ) 13 + ""\n miles driven is "" + suv.getMilesDriven( ) 14 + ""\n gallons of gas is "" + suv.getGallonsOfGas( ) ); 15 16 // call mutator method for each instance variable 17 suv.setModel( ""Sportage"" ); 18 suv.setMilesDriven( 200 ); 19 suv.setGallonsOfGas( 10.5 ); 20 21 // print new values of instance variables 22 System.out.println( ""\nsuv: model is "" + suv.getModel( ) 23 + ""\n miles driven is "" + suv.getMilesDriven( ) 24 + ""\n gallons of gas is "" + suv.getGallonsOfGas( ) ); 25 26 // attempt to set invalid value for milesDriven 27 suv.setMilesDriven( -1 ); 28 // print current values of instance variables 29 System.out.println( ""\nsuv: model is "" + suv.getModel( ) 30 + ""\n miles driven is "" + suv.getMilesDriven( ) 31 + ""\n gallons of gas is "" + suv.getGallonsOfGas( ) ); 32 } 33 } Here our client instantiates one Auto object, suv (line 9), and prints the values of its instance variables (lines 11-14). Then we call each mutator method, setting new values for each instance variable (lines 16-19). We again print the values of the instance variables (lines 21-24) to show that the values have been changed. Then, in line 27, we attempt to set an invalid value for milesDriven. As Figure 7.3 shows, the mutator method does not change the value, which we verify by again printing the values of the instance variables (lines 28-31). TIP Write the validation code for instance variables in mutator methods and have the constructor call the mutator methods to set initial values. Figure 7.3 Output from Auto Client, Version 3 suv: model is Trailblazer miles driven is 7000 gallons of gas is 437.5 suv: model is Sportage miles driven is 200 gallons of gas is 10.5 suv: model is Sportage miles driven is 200 gallons of gas is 10.5

toString Method Syntax Example

Example @Override public String toString() { return "Name" + name + "number of Objects" }

Driver object instance syntax Example

Example Auto suv = new Auto(); //Sets object name to default * miles to 0 & MPG to 0.0 or Auto truck = new Auto(F150,100,28); //Sets object name to F150 & miles to 100 & MPG to 28

UML Diagram Example

Example Create a Class Called BankAccount BankAccount - total : Double - firstName : String - lastName : String - SSN : Integer << Constructor >> BankAccount ( fName : String, lName : String, soc : Integer) + deposit ( amount : Double ) + withdraw ( amount : Double ) + toString ( ) : String Key: - private method + public method BankAccount.Java 1. public class BankAccount 2. { 3. private double total; 4. private String firstName; 5. private String lastName; 6. private int SSN; 7. public BankAccount ( String fName, String lName, int soc ) 8. { 9. 10. public void deposit ( double amount ) 11. { 12. } 13. public void withdraw ( double amount ) 14 { 15. } 16. public String toString ( ) 17. { 18. } 19. }

Constructor syntax Example

Example accessModifier ClassName( parameter list ) { // constructor body } Notice that a constructor has the same name as the class and has no return type—not even void. It's important to use the public access modifier for the constructors so that applications can instantiate objects of the class.

Class Defining Example

Example accessModifier class ClassName { // class definition goes here }

Instance Variables Example

Example accessModifier dataType identifierList; Examples: private String name = """"; // an empty String private final int PERFECT_SCORE = 100, PASSING_SCORE = 60;private int startX, startY, width, height;

Method Header Example

Example accessModifier returnType methodName( parameter list ) // method header { // method body } where parameter list is a comma-separated list of data types and variable names. Example: public static void main( String [ ] args ) { // application code }

Parameter List Example

Example public Auto ( String m, int md, double gg ) { setModel( m ); setMilesDriven( md ); setGallonsOfGas ( gg ); updateCount(); }

Object Reference This Example

Example public Auto setModel( String model ) { this.model = model; return this; }

Method Return type Example

Example public String getModel() { return this.model; }

Class header Example

Example public class Auto { }

Class name Example

Example public class Auto {

Scope Boundaries Example

Example public static void method() { for (int i = 1; i < 10; i++) //Scope of i starts here { int j; //Scope of j starts here } //Scope of i & j ends here }

Method name Example

Example public void setModel ( String mod ) {

Value return method Rule

Rules This method returns the result of the method using one or more return statements in the method body. The syntax for the return statement is "return expression". The data he data type of the expression must match the return type of the method. Recall that a value-returning method is called from an expression, and when the method completes its operation, its return value replaces the method call in the expression. If the data type of the method is void, as in main, we have a choice of using the return statement without an expression, as in this statement: return;or omitting the return statement altogether. Given that control automatically returns to the caller when the end of the method is reached, most programmers omit the return statement in void methods. Optionally, a return statement can be used if needed to exit a method before reaching the end of the method's code.

Public Access modifier Rules

Rules This modifier allows the class or member to be accessed by other classes. In other words, this modifier allows a method/variable to be accessible outside of the class it's declared in. "Methods" usually use this type of access modifier in their headers to allow access to the client.

Private Access modifier Rules

Rules This modifier specifies that the class or member can be accessed only by other members of the same class. By using this modifier, it WILL NOT ALLOW a method/variable to be accessible outside of the class it's declared in. "Attributes" generally use this type of access modifier in their headers to Deny access to the client. If the client attempts to access an attribute with this modifier, you will get a compiling error stating that your variable has no access in the java program.

Parameters Rules

Rules This part of a method is used to gather input that is necessary for the method to work correctly. At the end of a method header, you will see a set of parenthesis (). These are either empty or have a declaring variable inside of them. This variables value is originally located inside the main method, so calling it out here at the end of a new method is requesting the variable to be "passed inside" the new method so it can use it to do a calculation or test. Since its a variable, you will need to use its primitive name 1st, then the variable name itself. This ""m"" used in this example is defined inside of the constructor. So we are requesting to use it in this setter to test the user input then set the value = to the object instance variable. Just remember, these store the value from the argument into another variable, and it doesn't have to be the same variable that's used in the argument. These do not have to have the same name as the variable in which it is retrieving as input. Note: In other words, just because we named our variable x in the main method, doesn't mean we have to name it x in the parameter list. Ex. public void setMilesDriven ( int m ) { if ( m >= 0 ) { this.milesDriven = m; } }

Getter (Accessor) Syntax Rule

Rules This syntax DOES NOT have the word "void" in the header. Its purpose is to go find an instance variable and return its value when this method is called upon to do so. There is nothing declared in its parenthesis in the header. *You will need to make this kind of method for each instance variable Note: Remember this about this method Its only job is to retrieve a value at the instance, so it cant void anything and it has no value in the parenthesis **Syntax Ex. public int getMilesDriven(){ return milesDriven; { Special case - Static variables Ex. public static int getCount() //uses static in header { return countAutos; {

Setter (Mutator) Syntax Rule

Rules This syntax has the word ""void"" in the header. It also requires a new variable in the ending header parenthesis This new variable will do 1 of 2 things: 1. It will take the one of the instance variables and = it Ex. milesDriven = md; **Syntax public void setMilesDriven (int md){ milesDriven = md; } 2. It will be used for client input to set the instance variable to a value in an object after a conditional test is done making sure its a proper value. **Syntax public void setGallonsOfGas (double g){ if (g >= 0.0) { gallonsOfGas = g; } }

Graphical object Rules

Rules This type of object usually has instance variables for the starting (x, y) coordinate. It also provides a draw method that takes GraphicsContext objects as a parameter and includes the code to draw the graphical object.

Static class variables Rules

Rules This type of variable is created when the class is initialized. Thus, these variables exist before any objects are instantiated, and each class has only one copy of the class variables. Those that are constants are usually declared to be public because they typically are provided to allow the client to set preferences for the operations of a class.

Javadoc Rules

Rules This, which is part of the JDK, generates documentation for classes. To use this, you enclose a description of each class, method, and field in a block comment beginning with /** and ending with */. In addition, you can describe each parameter using the @param tag and return value using the @return tag.

Creating Objects with Classes Rules

Rules When doing this, these are created using a class's template. The syntax used as a new data type in the body of the class is similar to the familiar scanner declaration: Scanner input = new Scanner( System.in ); This process is written in a ""Driver"" program. It looks like this: Tree Maple = new Tree(); Note: In this example, we create a new program, called Tree.java, that creates a tree object. To create this object, we use the new data type, Tree the name we want to give this object (in this case, Maple), the equals sign, the keyword new, and finally the data type followed by parenthesis.

Class names rules

Rules When naming these, remember that they are nouns and should always begin with a capital letter; all internal words begin with a capital letter, and other letters are lowercase.

Public declared class structures

Structures Classes, constructors, final class variables, and class methods are declared as this (Typically - for 1st Java class)

Private declared class structure

Structures Instance variables are declared as this (Typically - for 1st Java class)

Accessor Methods (Getters) syntax

Syntax public returnType getInstanceVariable( ) { return instanceVariable; }

Mutator Methods (Setters) syntax

Syntax public void setInstanceVariable( dataType newValue ) { // validate newValue, then assign to the instance variable }

Class naming tips

Tips Coming up with the instance variables (set of characteristics) are the easiest part. Because it's how we caporegime the world. For example, If I wanted to describe a box, I would use height, width, depth, weight, volume, and color to name a quick few. There is 6 characteristics or Instance Variables that quick and easy. Then build your constructors. Ask yourself, ""How am I going to initialize those instance variables. And if you come up with a ""Static variable"", how can I initialize it also. Next, come up with your getters, which are usually straight forward. Then come up with your setters. Make sure you test your setters to make sure the setters do some integrity checking of the data. Then think about the facilitators and implement them. And as your writing code, as your writing, compile and test as you go along. Don't wait till you have a whole bunch of code then test. It makes harder to see when you have 17 different things then you try to compile but it won't. Ex. Make your instance variables, try to compile. See if it makes the object (Blue square) and all the components correctly. If not, work on why, then move on. If it does work, move on to adding in the constructors and test them too. Then write and test the getters, and setters, and facilitators. You can use the bottom window called Interactions to make the objects.

Validation Code Tip

Tips Write the validation code for instance variables in mutator methods and have the constructor call the mutator methods to set initial values.

3 Access Modifier Types

Types 1. public 2. private 3. protected These are used in the 1st part of a method header Ex. public static void Auto() Ex2. public class Auto() *Syntax of a method header access_modifier return_type method_name (parameter_list) { code return_statement (if applicable) }


Kaugnay na mga set ng pag-aaral

Module 4: Ecosystem Dynamics Part 1

View Set

09.03 Les villes et les pays Quiz

View Set

Gridlock in Congress- Causes and Solutions

View Set

cfa_cases_CommunicationWithClientsAndProspectiveClients_V(B)

View Set

exam 1 immunity infection inflammation

View Set