CSC 212 – Data Structures Lecture 12: Java Review
Fields Fields defined in class, but not in method Instances share fields; have different values Definition must also include a data type Can be primitive or reference type Fields behave like variables of that type would Fields should be private or protected In general, should be private protected allows subclasses to access field
javadoc Example /** This class represents individual cars that people drive. */ public class Car { /** * Name of company that made the car and name of the car model */ String makeAndModel; /** Color of the car. */ String color; /** How full the gas tank is, expressed as * a percentage. */ float tankLevel; /** Number of miles recorded on the odometer */ int odometerReading;
javadoc Example /** Reset the fuel tank to be full. */ public void fillTank() { tankLevel = 1.0; } /** * Change the amount of fuel by some means levelDelta Change in fuel level (as % of tank capacity) */ private void adjustFuel(float levelDelta) { tankLevel += levelAdded; /* Check that the tank level makes sense. */ if (tankLevel > 1.0) { tankLevel = 1.0; } else if (tankLevel < 0.0) { tankLevel = 0.0; } }
/** * Drive around town and look for the hot spots to hit. distance Number of miles traveled gasUsed Amount of fuel used on this trip */ public void crusin(int distance, float gasUsed) { int newDistance = odometerReading + distance; adjustFuel(gasUsed); odometerReading = newDistance; } /** * Find out if the car will start. Assumes that you will not hotwire the car. haveKey True if we the key to this car; else it is false True if the engine would start, false otherwise */ public boolean willStart(boolean haveKey) { if (!haveKey || tankLevel == 0.0) { return false; } else if (makeAndModel.startsWith(“Jaguar”)) { java.util.Random rnd = new Random(); return rnd.nextBoolean(); } else { return true; } }
Visibility Modifiers Going to class naked is common nightmare Try keeping certain details private Want control over our state Fields represent state of an object Fields normally declared private private int fieldName; Only access the field from class methods Use protected when subclass also accesses
Accessor Methods Field used in other classes’ methods Done via accessor methods (“getters”) Getter usually named getField public field_type getField() {... } Other classes must use accessor method Includes code that can limit access to field Do not copy code to each field use!
Mutator Methods Set field’s value in other classes’ methods Use mutator methods (“setters”) for this Setter usually named setField public void setField(field_type param) {... } Changes to field normally via mutators Check that only legal values assigned to field Makes changing or updating checks easier
Visibility of Methods Methods normally act on or with object Use active verb as name Declare as public Replace multiple copies of code with single method Perform common test, update, or calculation These should be private or protected Simplifies using and editing the class
Fields Each class instance has fields Field values in separate instances may * differ Static fields shared by all instances Objects’ fields initialized at instantiation Initial value is 0, false, ‘’, or null Should define as few fields as possible Do not include fields that can be computed Unneeded fields makes coding harder
Parameters Variables named in method description Created & initialized each time method called “Live” until method completes Initialized with value of argument Primitives copy value into parameter References parameter aliases argument Documented as part of method comments Done paramName paramDescript
Locals Variables declared inside a method Required to assigned value before using “Live” only for code block in which declared Cannot be included in javadoc Local variables help a method complete Only comment as part of describing how method works
Tracing Parameters public void badTransfer(BankAccount source, float amount) { if (amount >= source.balance) { amount = source.balance(); source = null; } else { source.balance -= amount; } balance += amount; } check.badTransfer(richOne, ); owner balance 0.05 identifier “2408” check haxx0r owner balance identifier “2408” richOne this source amount balance
Tracing Parameters public void badTransfer(BankAccount source, float amount) { if (amount >= source.balance) { amount = source.balance(); source = null; } else { source.balance -= amount; } balance += amount; } check.badTransfer(richOne, Float.MAX_VALUE); owner balance identifier “2408” check haxx0r owner balance identifier “2408” richOne this source amount ~3.4·10 38
Inherited Fields & Methods Subclass inherits superclass’s methods and fields Non-private fields and methods used as if in subclass Can reuse names in subclasses Fields are hidden Methods are overriden Method called according to instance type Fields accessed by variable type
this & super Keywords this keyword is rarely used in Java Access field with same name as parameter or local From constructor call another defined in class Usage of super within constructor Must be first statement in constructor Calls constructor defined in superclass Usage of super elsewhere in class Call overriden method as defined in superclass: super.methodName(…); Use hidden field as defined in superclass: super.fieldName;
Before Next Lecture… Start week #5 assignment Continue programming assignment #1 It is due Friday Start reviewing for Midterm #1 It will be 1 week from today Wednesday’s lecture talks about linked lists Read Sections of the book