CSC 212 – Data Structures Lecture 3: Fields, Methods, & Constructors
Problem of the Day Why are manhole covers round? It is the only shape that guarantees that the cover cannot fall in!
Announcements Still need a note-taker; please see me if you are interested in the $50 If you feel this Java review is going too fast talk to me, check out the pages from the “Links” page, and/or seek out additional resources
Classes vs. Objects Classes are recipes or blueprints which describe a data type Classes (usually) cannot do anything on their own Objects are the instances of the class New object created (instantiated) by new Fields describe object’s state Methods represent object’s behavior
Fields Fields are defined by a class All instances of class have same fields… … but fields’ values may differ Fields in a class must have unique name But same name okay if in different classes Definition must also include a data type Can be primitive or reference type Fields behave like variables of that type would
Class Example 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; /* Definition continues from here */
Using Fields (1) Car profHertzCar = new Car(); profHertzCar.makeAndModel = “BMW Z4”; profHertzCar.color = “Deep Green Metallic”; profHertzCar.tankLevel = 1.0; profHertzCar.odometerReading = 10000; Car shoshannaCar = new Car(); shoshannaCar.makeAndModel = “Ford Taurus Wagon”; shoshannaCar.color = “Silver”; shoshannaCar.tankLevel = ; shoshannaCar.odometerReading = ;
Using Fields (2) Car dreamCar = new Car(); dreamCar.makeAndModel = “BMW Z4”; dreamCar.color = “Deep Green Metallic”; dreamCar.tankLevel = 1.0; dreamCar.odometerReading = 10000; Car realCar = dreamCar; realCar.makeAndModel = “Ford Taurus Wagon”; realCar.color = “Silver”; realCar.tankLevel = ; realCar.odometerReading = ;
Methods All Java code is defined within a class Define actions & behavior of objects Also specify how object’s state should change Methods must have unique name and parameter list (“signature”) Two methods can share name Methods also define return type Return type is not part of signature, however
Method Return Types Return type could be a primitive, reference, array, or void void methods cannot return data Other methods must return data Method immediately stops at return Will not compile if: Code continues after return Possible to end non-void method without`` return
Car Example /** Reset the fuel tank to be full. */ void fillTank() { tankLevel = 1.0; } /** * Change the amount of fuel by some means levelDelta Change in fuel level (as % of tank capacity) */ void adjustFuel(float levelDelta) { tankLevel += levelDelta; /* 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 */ 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 */ 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; } }
Using Methods Car dreamCar = new Car(); Car realCar = dreamCar; dreamCar.makeAndModel = “BMW Z4”; dreamCar.color = “Deep Green Metallic”; dreamCar.tankLevel = 1.0; dreamCar.odometerReading = 10000; if (dreamCar.willStart(true)) { System.out.println(“Vroom vroom”); } realCar.crusin(400, -1.0); if (dreamCar.willStart(true)) { System.out.println(“Vroom vroom”); } else { System.out.println(“*sigh*”); }
Constructors Special methods called only when instantiating an object Must have identical name as class Cannot include a return type (include void) Can define multiple constructors with different signatures Parameters used in new must match at least 1 constructor
Car Example /** * Create a new car with the given make, model, color and tankLevel. make Manufacturer of the car being created model Model of the car being instantiated color Color to which the car should be painted pctFull How full the gas tank is (in % of capacity terms) */ Car(String make, String model, String color, float pctFull) { // Set car’s make and model makeAndModel = make + “ “ + model; // Record the color this.color = color; // Set the tank level adjustFuel(pctFull); // New cars have not driven anywhere, yet this.odometerReading = 0; }
Using Constructors Car profHertzCar = new Car(); profHertzCar.makeAndModel = “BMW Z4”; profHertzCar.color = “Deep Green Metallic”; profHertzCar.tankLevel = 1.0; profHertzCar.odometerReading = 10000; Car profHertzCar = new Car(“BMW”, “Z4”, “Deep Green Metallic”, 1.0); profHertzCar.odometerReading = 10000; /* This causes an error, since there is not a constructor that takes two String parameters. */ Car badCar = new Car(“BMW”, “Z4”);
Before Next Lecture… Finish week #1 homework Wednesday’s lecture will continue with constructors, fields, & methods Keep thinking & ask any questions you have May want to review any old notes & handouts