Download presentation
Presentation is loading. Please wait.
Published byPreston Barnett Modified over 9 years ago
1
Question of the Day What card(s) must you flip to verify the following statement: Cards with a vowel on one side, have an even number on the other side. A A B B 4 4 7 7
2
Question of the Day What card(s) must you flip to verify the following statement: Cards with a vowel on one side, have an even number on the other side. A A B B 4 4 7 7
4
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
5
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
6
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
7
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 */
8
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;
9
Using Fields (2) Car dreamCar = new Car(); dreamCar.makeAndModel = “BMW Z4”; dreamCar.color = “Deep Green Metallic”; dreamCar.tankLevel = 1.0; dreamCar.odometerReading = 10000;
10
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 = “Subaru Outback”; realCar.color = “Silver”; realCar.tankLevel = 0.0001; realCar.odometerReading = 45634;
11
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 = “Subaru Outback”; realCar.color = “Silver”; realCar.tankLevel = 0.0001; realCar.odometerReading = 45634;
12
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
13
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
14
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; } }
15
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; } }
16
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*”); }
17
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
18
Tracing with Objects public class Account { public String own; public float bal; public String id; Account check = new Account(“haxx0r”, 1.25, “0001”); Account richOne = new Account(“billG”,9000000,“2408”); check.bal -= 1.20; // Bought a coffee check.id = “2408”; // 1 st theft attempt richOne.own = “haxx0r”; // 2 nd theft attempt
19
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
20
Tracing Parameters public void badTransfer(Account src,float amt){ if (amt >= src.bal) { amt = src.bal (); src = null; } else { src.bal -= amt; } bal += amt; } check.badTransfer(richOne, Float.MAX_VALUE);
21
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
22
Locals Variables declared inside a method Must be assigned value before using “Live” only for code block in which declared Local variable always better than field 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 Never declare a field when a local will do
23
Locals Variables declared inside a method Must be assigned value before using “Live” only for code block in which declared Local variable always better than field 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
24
Locals Variables declared inside a method Must be assigned value before using “Live” only for code block in which declared Local variable always better than field 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
25
Locals Variables declared inside a method Must be assigned value before using “Live” only for code block in which declared Local variable always better than field 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
26
Locals Variables declared inside a method Must be assigned value before using “Live” only for code block in which declared Local variable always better than field 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
27
Calling Methods Some methods really need an object Integer. intValue() is unclear without an object But other methods independent of an instance main(String[]) lacks an object to use to call it Why need Integer to call parseInt(String) ?
28
static Methods static methods do not need an instance Behavior defined by class, not an instance parseInt(String) based only on Integer All methods similar in how written & executed May or may not include parameters Local variables can be declared and used Must either be void or declare return type Mix of methods possible for all classes & enums
29
Making Method static Include static keyword in method declaration public static void main(String args[]) public static int parseInt(String s) private static int nextInt() Behaves like any other method (almost) Use locals & parameters like normal As with other code, call (nearly all) other methods Java operators can be used Perform any I/O operations
30
static v. Non- static Methods that are non- static have this Aliased to instance on which method called Can directly use fields & call all methods No this parameter in static methods Code directly using non- static members illegal… … using static fields & methods perfectly legal As always, can use object to access its members
31
BadDuck public class BadDuck { private int quackVolume; public static void printVolume() { System.out.println(“Volume is ” + getVolume()); BadDuck duck = new BadDuck(); duck.quackVolume = 11; System.out.println(“Volume is ”+duck.getVolume()); } public int getVolume() { return quackVolume; } }
32
BadDuck getVolume() public class BadDuck { private int quackVolume; public static void printVolume() { System.out.println(“Volume is ” + getVolume()); BadDuck duck = new BadDuck(); duck.quackVolume = 11; System.out.println(“Volume is ”+duck.getVolume()); } public int getVolume() { return quackVolume; } } Compiler error. Without an object, whose volume are we getting?
33
BadDuck getVolume() public class BadDuck { private int quackVolume; public static void printVolume() { System.out.println(“Volume is ” + getVolume()); BadDuck duck = new BadDuck(); duck.quackVolume = 11; System.out.println(“Volume is ”+duck.getVolume()); } public int getVolume() { return quackVolume; } } This is good. There is a duck to get the volume.
34
BadDuck public class BadDuck { public static String duckSpeak() { return “quack”; } } public class UseDuck { public void speak() { System.out.println(BadDuck.duckSpeak()); BadDuck duck = new BadDuck(); System.out.println(duck.duckSpeak()); } }
35
BadDuck public class BadDuck { public static String duckSpeak() { return “quack”; } } BadDuck.duckSpeak() public class UseDuck { public void speak() { System.out.println(BadDuck.duckSpeak()); BadDuck duck = new BadDuck(); System.out.println(duck.duckSpeak()); } } This compiles. Static methods do not use an object, so this is preferred way to call them.
36
BadDuck public class BadDuck { public static String duckSpeak() { return “quack”; } } duck.duckSpeak() public class UseDuck { public void speak() { System.out.println(BadDuck.duckSpeak()); BadDuck duck = new BadDuck(); System.out.println(duck.duckSpeak()); } } Also fine, but since method is static, still cannot access instance.
37
static Fields Some data belongs to class, not instance Float.MAX_VALUE Citizen.nationalPopulation Instructor.bestProfessor static fields used for any class-based data All of the class instances see same value Do not need an instance to access this value Can be updated via any instance or via class
38
static Code for Tracing public class Player { private static int num; private static String champ; private String name; public Player(String newN) { num += 1; name = newN; } public static int getPlayers() { return num; } public static String setChamp(String best) { champion = best; } }
39
Tracing With Statics public void startGame() { Player player1, player2, player3; player1 = new Player(“Homer”); player2 = new Player(“Joey JoJo”); player3 = player2; Player.champ = “Homer”; player2.setChamp (“Joey JoJo”); }
40
static v. non- static Review Difference between static & non- static static members belong to the class Accessing & using member possible without instance Methods lack implicit this parameter no matter what Instances required for non- static member Fields’ data instance-specific and not shared by class Can access all members using implicit this parameter
41
Your Turn Get into your groups and complete activity
42
For Next Lecture Keep reviewing your Java lessons Will be doing some fun & different problems Monday Really need to be back up-to-speed at that point There is weekly assignment problem on Angel Due before Monday’s lecture (via e-mail) With this finish removing rust from lazy summer
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.