csc 212 – data structures lecture 3: fields, methods, & constructors

17
CSC 212 – Data Structures Lecture 3: Fields, Methods, & Constructors

Upload: theodore-daniel

Post on 26-Dec-2015

218 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: CSC 212 – Data Structures Lecture 3: Fields, Methods, & Constructors

CSC 212 –Data Structures

Lecture 3:

Fields, Methods, & Constructors

Page 2: 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!

Page 3: CSC 212 – Data Structures Lecture 3: Fields, Methods, & Constructors

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

Page 4: CSC 212 – Data Structures Lecture 3: Fields, Methods, & Constructors

Classes vs. Objects

Classes are recipes or blueprints which describe a data typeClasses (usually) cannot do anything on their own

Objects are the instances of the classNew object created (instantiated) by newFields describe object’s stateMethods represent object’s behavior

Page 5: CSC 212 – Data Structures Lecture 3: Fields, Methods, & Constructors

Fields

Fields are defined by a classAll instances of class have same fields…… but fields’ values may differ

Fields in a class must have unique nameBut same name okay if in different classes

Definition must also include a data typeCan be primitive or reference typeFields behave like variables of that type would

Page 6: CSC 212 – Data Structures Lecture 3: Fields, Methods, & Constructors

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 */

Page 7: CSC 212 – Data Structures Lecture 3: Fields, Methods, & Constructors

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 = 0.0001;shoshannaCar.odometerReading = 175634;

Page 8: CSC 212 – Data Structures Lecture 3: Fields, Methods, & Constructors

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 = 0.0001;realCar.odometerReading = 175634;

Page 9: CSC 212 – Data Structures Lecture 3: Fields, Methods, & Constructors

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 typeReturn type is not part of signature, however

Page 10: CSC 212 – Data Structures Lecture 3: Fields, Methods, & Constructors

Method Return Types

Return type could be a primitive, reference, array, or voidvoid methods cannot return dataOther methods must return data

Method immediately stops at return Will not compile if:

Code continues after returnPossible to end non-void method without`` return

Page 11: CSC 212 – Data Structures Lecture 3: Fields, Methods, & Constructors

Car Example <cont.>

/** Reset the fuel tank to be full. */void fillTank() { tankLevel = 1.0;}

/** * Change the amount of fuel by some means * @param 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; }}

Page 12: CSC 212 – Data Structures Lecture 3: Fields, Methods, & Constructors

/** * Drive around town and look for the hot spots to hit. * @param distance Number of miles traveled * @param 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. * @param haveKey True if we the key to this car; else it is false * @return 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; }}

Page 13: CSC 212 – Data Structures Lecture 3: Fields, Methods, & Constructors

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*”);}

Page 14: CSC 212 – Data Structures Lecture 3: Fields, Methods, & Constructors

Constructors

Special methods called only when instantiating an objectMust have identical name as classCannot include a return type (include void)Can define multiple constructors with different

signatures Parameters used in new must match at

least 1 constructor

Page 15: CSC 212 – Data Structures Lecture 3: Fields, Methods, & Constructors

Car Example <cont.>

/** * Create a new car with the given make, model, color and tankLevel. * @param make Manufacturer of the car being created * @param model Model of the car being instantiated * @param color Color to which the car should be painted * @param 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;}

Page 16: CSC 212 – Data Structures Lecture 3: Fields, Methods, & Constructors

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”);

Page 17: CSC 212 – Data Structures Lecture 3: Fields, Methods, & Constructors

Before Next Lecture…

Finish week #1 homework Wednesday’s lecture will continue with

constructors, fields, & methodsKeep thinking & ask any questions you haveMay want to review any old notes & handouts