Download presentation
Presentation is loading. Please wait.
Published byKelly Berry Modified over 9 years ago
2
Announcements If you need more review of Java… I have lots of good resources – talk to me Use “Additional Help” link on webpage Weekly assignments problems due before class Remove rust from summer and get back into coding Problems designed to help learn new material, too
3
Classes vs. Objects Classes are blueprints describing data type Classes (usually) cannot do anything on their own Objects are instances of a class New objects created (instantiated) using new Fields describe state of an object Object’s behavior represented by methods
4
Instance Variables All of class's instances have same fields… … but values can differ between each instance In a class, each field must have unique name Different classes can duplicate names of fields Field declaration also includes data type Will act like variables of that type Can be primitive, enum, or reference type
5
Class Example public class Car { /** What kind of car & who made it */ private String makeAndModel; /** Color of the car. */ private String color; /** Percent full the gas tank is */ private float tankLevel; /** Miles recorded on the odometer */ private int odometerReading; /* Definition continues from here */
6
Using Fields (1) Car profHertzCar = new Car(); profHertzCar.makeAndModel = “BMW Z4”; profHertzCar.color = “Deep Green Metallic”; profHertzCar.tankLevel = 1.0; profHertzCar.odometerReading = 10000; Car actualCar = new Car(); actualCar.makeAndModel = “Subaru Outback"; actualCar.color = “Brown”; actualCar.tankLevel = 0.0001; actualCar.odometerReading = 47634;
7
Using Fields (2) Car dreamCar = new Car(); dreamCar.makeAndModel = “BMW Z4”; dreamCar.color = “Deep Green Metallic”; dreamCar.tankLevel = 1.0; dreamCar.odometerReading = 10000;
8
Methods Define how objects act, behave, & change Need unique name & parameters (“signature”) Can share name or parameter list, but not both Determines which code used at any method call Methods also define return type Return type is not part of signature Cannot help determine which method to call
9
Method Return Types Can be primitive, reference, array, or void void methods cannot return data All other methods must return data Method execution stops immediately at return Will NOT execute further in method After return, calling method executes immediately Compilation error occurs when: Method includes executing code after return Non- void method can end without return statement
10
Car Example /** Reset the fuel tank to be full. */ void fillTank() { tankLevel = 1.0; } /** Change amount of fuel by some means * @param levelDelta Change in fuel level */ void adjustFuel(float levelDelta) { tankLevel += levelDelta; /* Check that tank level makes sense. */ if (tankLevel > 1.0) { tankLevel = 1.0; } else if (tankLevel < 0.0) { tankLevel = 0.0; } }
11
Useful Car Methods void crusin(int distance, float gasUsed) { int newDistance = odometerReading + distance; adjustFuel(gasUsed); odometerReading = newDistance; } 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; } }
12
Calling Methods Car dreamCar = new Car(); 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”); } dreamCar.crusin(400, 1.0); if (dreamCar.willStart(true)) { System.out.println(“Vroom vroom”); } else { System.out.println(“*sigh*”); }
13
Constructors Special methods called to instantiate object Have identical name as class No return type (not even void ) allowed If parameters differ, multiple constructors possible Parameters to new must match 1 constructor If no constructor defined, implicit one used for class No parameters included in implicit constructor
14
Tracing with Objects public class Account { public String owner; public float balance; public String identifier; Account check = new Account(“haxx0r”, 1.25, “0001”); Account richOne = new Account(“billG”,9000000,“2408”); check.balance -= 1.20; // Bought a coffee check.identifier = “2408”; // 1 st theft attempt richOne.owner = “haxx0r”; // 2 nd theft attempt
15
Tracing Parameters Traced like variable created at method call New variable created each time method called Variable lives until completion of method Initialized with value of argument Works like ran parameter = actual Primitives copy value into parameter Parameter is aliased if a reference
16
Tracing Parameters public void badTransfer(Account source,float amount){ if (amount >= source.balance) { amount = source.balance(); source = null; } else { source.balance -= amount; } balance += amount; } check.badTransfer(richOne, Float.MAX_VALUE);
17
Locals Variables declared inside a method Must be assigned value before using “Live” only for code block in which declared Local always better than instance variable Easy trick to simplify design, algorithm, & code Reduces opportunities for bugs dramatically Added bonus, creates fewer comments to write! Declare local in smallest enclosing block
18
Your Turn Get into your groups and complete activity
19
For Next Lecture Reading from AF 7.11 for Wednesday What does the static keyword mean? How do static fields & static methods work? Why did 10 out of 12 students get this wrong? There is weekly assignment problem on Angel Due before Wednesday’s lecture (via e-mail) Get back into the swing of writing Java code
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.