Download presentation
Presentation is loading. Please wait.
1
Lecture 3: Fields, Methods, & Constructors
CSE 116/504 – Intro. To Computer Science for Majors II Lecture 3: Fields, Methods, & Constructors
2
Announcements 130 students (64%) joined Piazza as of 9AM
Important since used for important announcements Sign up today to avoid problems later on
3
SIGN UP TODAY Announcements 130 students (64%) joined Piazza as of 9AM
Important since used for important announcements Sign up today to avoid problems later on
6
Today’s Goals Experiments with TopHat before grading begins
Portion of course grade & that starts counting on Wed. Review object workings & use in more detail Remember how methods called & what this does return statement reviewed & its importance in code Passing arguments to method & what parameter does Use of fields within method & what effects would be
7
Ice Cream Flavor(s) You Like
Chocolate Vanilla Peanut Butter Chunk Banana Sardine and Sauerkraut
8
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
9
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 must include data type Primitive or reference type can be used; either legal Field ends up behaving like other primitive or reference
10
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 */
11
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 = ; actualCar.odometerReading = ;
12
Each instance gets own copy of instance variables
Fields Key Concept #1 Each instance gets own copy of instance variables
13
Using Fields (2) Car dreamCar = new Car(); dreamCar.makeAndModel = “BMW Z4”; dreamCar.color = “Deep Green Metallic”; dreamCar.tankLevel = 1.0; dreamCar.odometerReading = 10000;
14
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 = ; realCar.odometerReading = 67634;
15
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 = ; realCar.odometerReading = ;
16
Each instance gets own copy of instance variables
Fields Key Concept #1++ Each instance gets own copy of instance variables
17
Aliased variables see ALL changes to instance variables
Fields Key Concept #2 Aliased variables see ALL changes to instance variables
18
Using Fields (3) Car dreamCar = new Car(); dreamCar.makeAndModel = “BMW Z4”; dreamCar.color = “Deep Green Metallic”;
19
Using Fields (3) Car dreamCar = new Car(); dreamCar.makeAndModel = “BMW Z4”; dreamCar.color = “Deep Green Metallic”; Car realCar = new Car(); realCar.makeAndModel = “Subaru Outback”; realCar.color = dreamCar.color;
20
Using Fields (3) Car dreamCar = new Car(); dreamCar.makeAndModel = “BMW Z4”; dreamCar.color = “Deep Green Metallic”; Car realCar = new Car(); realCar.makeAndModel = “Subaru Outback”; realCar.color = dreamCar.color; realCar.odometerReading = ; realCar.tankLevel = dreamCar.tankLevel;
21
Fields Key Concept #3 Fields initialized to default value of 0, false, or null (almost all other variables need assignment before use)
22
Tracing With Fields Each instance gets own copy of instance variables
Show in instance’s box, otherwise like other variables Primitive values in instance & get copied on assignment Assignments make alias; references shown as arrow
23
Tracing With Fields Each instance gets own copy of instance variables
Show in instance’s box, otherwise like other variables Primitive values in instance & get copied on assignment Assignments make alias; references shown as arrow
24
Tracing With Fields public class Player { private int num; private Player backup; public static void main(String[] args) { Player player1, player2, player3; player1 = new Player(); player1.num = 33; player2 = new Player(); player2.num = 42; player2.backup = player1; player3 = player1; player3.num = 68; }
25
Instance Variables Review
Each instance gets own copy of every field Must specify instance whose field should be used Within code, instance can update value at any time No limit on use in code, but need the instance As with any variable, primitive or reference okay Declare anywhere outside of method (but in class): type name;
26
Methods Define how objects act, behave, & change
Every method in class must have unique signature Method name or parameter's order&type must differ Important for code: makes obvious which to execute Return type also need to be declared by methods Cannot be only difference: type not part of signature Caller can skip using result, so does not help find method
27
Return Type Methods must specify their return type
Primitive or reference type if they will return 1 value double squareIt(float x); ArrayList<String> primes(int n); Professor getFavoriteTeacher(); Special return type, void, used if no value is returned void goodSoldier(); void doSomethingWithX(int x);
28
return Examples void moveAlong() { System.out.println("Nothing to see here"); return null; } float squared(int val) { double retVal = val * (double)val; return retVal; } String getRandomLetter() { java.util.Random rand = new Random(); char ch = (char)rand.nextInt(); return "\'" + ch + "\'"; ch = Character.toLowerCase(ch); }
29
return Examples void moveAlong() { System.out.println("Nothing to see here"); return null; } float squared(int val) { double retVal = val * (double)val; return retVal; } String getRandomLetter() { java.util.Random rand = new Random(); char ch = (char)rand.nextInt(); return "\'" + ch + "\'"; ch = Character.toLowerCase(ch); }
30
return Examples void moveAlong() { System.out.println("Nothing to see here"); } float squared(int val) { double retVal = val * (double)val; return retVal; } String getRandomLetter() { java.util.Random rand = new Random(); char ch = (char)rand.nextInt(); return "\'" + ch + "\'"; ch = Character.toLowerCase(ch); }
31
return Examples void moveAlong() { System.out.println("Nothing to see here"); } float squared(int val) { double retVal = val * (double)val; return retVal; } String getRandomLetter() { java.util.Random rand = new Random(); char ch = (char)rand.nextInt(); return "\'" + ch + "\'"; ch = Character.toLowerCase(ch); }
32
return Examples void moveAlong() { System.out.println("Nothing to see here"); } float squared(int val) { double retVal = val * (double)val; return retVal; } String getRandomLetter() { java.util.Random rand = new Random(); char ch = (char)rand.nextInt(); return "\'" + ch + "\'"; ch = Character.toLowerCase(ch); }
33
return Examples void moveAlong() { System.out.println("Nothing to see here"); } float squared(int val) { long retVal = val * val; return retVal; } String getRandomLetter() { java.util.Random rand = new Random(); char ch = (char)rand.nextInt(); return "\'" + ch + "\'"; ch = Character.toLowerCase(ch); }
34
return Examples void moveAlong() { System.out.println("Nothing to see here"); } float squared(int val) { long retVal = val * val; return retVal; } String getRandomLetter() { java.util.Random rand = new Random(); char ch = (char)rand.nextInt(); return "\'" + ch + "\'"; ch = Character.toLowerCase(ch); }
35
return Statement Function ends when return gets executed
Value in return statement is result from method Calling function resumes execution from the method call If executable code is after return, Java will not compile
36
return Statement Key Concept
37
Return Value If value returned, either a primitive or reference
Call "evaluates" to return value when line gets executed Debugging & reuse value by setting variable to result Object aliased in assignment, if return value reference If return value is primitive, result copied into variable Nothing returned by void method, no result to use Remember: will get error trying to return from void Error using result of void method call, by extension
38
Method Call Examples void drive() { /* Code skipped for space */ } float checkGas(double added) { /* Code skipped for space */ } Car getDreamCar() { /* Code skipped for space */ } int distanceMoved = drive(); drive(); Object obj = drive(); if (checkGas(0.2) < checkGas(-0.1)) System.out.println("I think we have a problem"); checkGas(fillUp) = 1.0; Car tesla = getDreamCar(); if (getDreamCar().odometer > ) { System.out.println("I'll wait"); getDreamCar() = null; }
39
Method Call Examples void drive() { /* Code skipped for space */ } float checkGas(double added) { /* Code skipped for space */ } Car getDreamCar() { /* Code skipped for space */ } int distanceMoved = drive(); drive(); Object obj = drive(); if (checkGas(0.2) < checkGas(-0.1)) System.out.println("I think we have a problem"); checkGas(fillUp) = 1.0; Car tesla = getDreamCar(); if (getDreamCar().odometer > ) { System.out.println("I'll wait"); getDreamCar() = null; }
40
Method Call Examples void drive() { /* Code skipped for space */ } float checkGas(double added) { /* Code skipped for space */ } Car getDreamCar() { /* Code skipped for space */ } int distanceMoved = drive(); drive(); Object obj = drive(); if (checkGas(0.2) < checkGas(-0.1)) System.out.println("I think we have a problem"); checkGas(fillUp) = 1.0; Car tesla = getDreamCar(); if (getDreamCar().odometer > ) { System.out.println("I'll wait"); getDreamCar() = null; }
41
Method Call Examples void drive() { /* Code skipped for space */ } float checkGas(double added) { /* Code skipped for space */ } Car getDreamCar() { /* Code skipped for space */ } int distanceMoved = drive(); drive(); Object obj = drive(); if (checkGas(0.2) < checkGas(-0.1)) System.out.println("I think we have a problem"); checkGas(fillUp) = 1.0; Car tesla = getDreamCar(); if (getDreamCar().odometer > ) { System.out.println("I'll wait"); getDreamCar() = null; }
42
Method Call Examples void drive() { /* Code skipped for space */ } float checkGas(double added) { /* Code skipped for space */ } Car getDreamCar() { /* Code skipped for space */ } int distanceMoved = drive(); drive(); Object obj = drive(); if (checkGas(0.2) < checkGas(-0.1)) System.out.println("I think we have a problem"); checkGas(fillUp) = 1.0; Car tesla = getDreamCar(); if (getDreamCar().odometer > ) { System.out.println("I'll wait"); getDreamCar() = null; }
43
Method Call Examples void drive() { /* Code skipped for space */ } float checkGas(double added) { /* Code skipped for space */ } Car getDreamCar() { /* Code skipped for space */ } int distanceMoved = drive(); drive(); Object obj = drive(); if (checkGas(0.2) < checkGas(-0.1)) System.out.println("I think we have a problem"); checkGas(fillUp) = 1.0; Car tesla = getDreamCar(); if (getDreamCar().odometer > ) { System.out.println("I'll wait"); getDreamCar() = null; }
44
Method Call Examples void drive() { /* Code skipped for space */ } float checkGas(double added) { /* Code skipped for space */ } Car getDreamCar() { /* Code skipped for space */ } int distanceMoved = drive(); drive(); Object obj = drive(); if (checkGas(0.2) < checkGas(-0.1)) System.out.println("I think we have a problem"); checkGas(fillUp) = 1.0; Car tesla = getDreamCar(); if (getDreamCar().odometer > ) { System.out.println("I'll wait"); getDreamCar() = null; }
45
Method Calling Key Concept #1
46
Method Call Examples void drive() { /* Code skipped for space */ } float checkGas(double added) { /* Code skipped for space */ } Car getDreamCar() { /* Code skipped for space */ } int distanceMoved = drive(); drive(); Object obj = drive(); if (checkGas(0.2) < checkGas(-0.1)) System.out.println("I think we have a problem"); checkGas(fillUp) = 1.0; Car tesla = getDreamCar(); if (getDreamCar().odometer > ) { System.out.println("I'll wait"); getDreamCar() = null; }
47
Method Call Examples void drive() { /* Code skipped for space */ } float checkGas(double added) { /* Code skipped for space */ } Car getDreamCar() { /* Code skipped for space */ } int distanceMoved = drive(); drive(); Object obj = drive(); if (checkGas(0.2) < checkGas(-0.1)) System.out.println("I think we have a problem"); checkGas(fillUp) = 1.0; Car tesla = getDreamCar(); if (getDreamCar().odometer > ) { System.out.println("I'll wait"); getDreamCar() = null; }
48
Method Call Examples void drive() { /* Code skipped for space */ } float checkGas(double added) { /* Code skipped for space */ } Car getDreamCar() { /* Code skipped for space */ } int distanceMoved = drive(); drive(); Object obj = drive(); if (checkGas(0.2) < checkGas(-0.1)) System.out.println("I think we have a problem"); checkGas(fillUp) = 1.0; Car tesla = getDreamCar(); if (getDreamCar().odometer > ) { System.out.println("I'll wait"); getDreamCar() = null; }
49
Method Call Examples void drive() { /* Code skipped for space */ } float checkGas(double added) { /* Code skipped for space */ } Car getDreamCar() { /* Code skipped for space */ } int distanceMoved = drive(); drive(); Object obj = drive(); if (checkGas(0.2) < checkGas(-0.1)) System.out.println("I think we have a problem"); checkGas(fillUp) = 1.0; Car tesla = getDreamCar(); if (getDreamCar().odometer > ) { System.out.println("I'll wait"); getDreamCar() = null; }
50
Method Call Examples void drive() { /* Code skipped for space */ } float checkGas(double added) { /* Code skipped for space */ } Car getDreamCar() { /* Code skipped for space */ } int distanceMoved = drive(); drive(); Object obj = drive(); if (checkGas(0.2) < checkGas(-0.1)) System.out.println("I think we have a problem"); checkGas(fillUp) = 1.0; Car tesla = getDreamCar(); if (getDreamCar().odometer > ) { System.out.println("I'll wait"); getDreamCar() = null; }
51
Method Calling Key Concept #2
Calls cannot be on left-hand side of assignment Ignore what we are using in the return statement. It is the VALUE of a field or variable that is returned, not the variable itself
52
Method Call Examples void drive() { /* Code skipped for space */ } float checkGas(double added) { /* Code skipped for space */ } Car getDreamCar() { /* Code skipped for space */ } int distanceMoved = drive(); drive(); Object obj = drive(); if (checkGas(0.2) < checkGas(-0.1)) System.out.println("I think we have a problem"); checkGas(fillUp) = 1.0; Car tesla = getDreamCar(); if (getDreamCar().odometer > ) { System.out.println("I'll wait"); getDreamCar() = null; }
53
Method Call Examples void drive() { /* Code skipped for space */ } float checkGas(double added) { /* Code skipped for space */ } Car getDreamCar() { /* Code skipped for space */ } int distanceMoved = drive(); drive(); Object obj = drive(); if (checkGas(0.2) < checkGas(-0.1)) System.out.println("I think we have a problem"); checkGas(fillUp) = 1.0; Car tesla = getDreamCar(); if (getDreamCar().odometer > ) { System.out.println("I'll wait"); getDreamCar() = null; }
54
Method Call Examples void drive() { /* Code skipped for space */ } float checkGas(double added) { /* Code skipped for space */ } Car getDreamCar() { /* Code skipped for space */ } int distanceMoved = drive(); drive(); Object obj = drive(); if (checkGas(0.2) < checkGas(-0.1)) System.out.println("I think we have a problem"); checkGas(fillUp) = 1.0; Car tesla = getDreamCar(); if (getDreamCar().odometer > ) { System.out.println("I'll wait"); getDreamCar() = null; }
55
Method Call Examples void drive() { /* Code skipped for space */ } float checkGas(double added) { /* Code skipped for space */ } Car getDreamCar() { /* Code skipped for space */ } int distanceMoved = drive(); drive(); Object obj = drive(); if (checkGas(0.2) < checkGas(-0.1)) System.out.println("I think we have a problem"); checkGas(fillUp) = 1.0; Car tesla = getDreamCar(); if (getDreamCar().odometer > ) { System.out.println("I'll wait"); getDreamCar() = null; }
56
Method Calling Key Concept #3
Can use result of method call just like any value (but this is bad style, so don't)
57
Method Call Examples void drive() { /* Code skipped for space */ } float checkGas(double added) { /* Code skipped for space */ } Car getDreamCar() { /* Code skipped for space */ } int distanceMoved = drive(); drive(); Object obj = drive(); if (checkGas(0.2) < checkGas(-0.1)) System.out.println("I think we have a problem"); checkGas(fillUp) = 1.0; Car tesla = getDreamCar(); if (getDreamCar().odometer > ) { System.out.println("I'll wait"); getDreamCar() = null; }
58
Method Call Examples void drive() { /* Code skipped for space */ } float checkGas(double added) { /* Code skipped for space */ } Car getDreamCar() { /* Code skipped for space */ } int distanceMoved = drive(); drive(); Object obj = drive(); if (checkGas(0.2) < checkGas(-0.1)) System.out.println("I think we have a problem"); checkGas(fillUp) = 1.0; Car tesla = getDreamCar(); if (getDreamCar().odometer > ) { System.out.println("I'll wait"); getDreamCar() = null; }
59
Method Call Examples void drive() { /* Code skipped for space */ } float checkGas(double added) { /* Code skipped for space */ } Car getDreamCar() { /* Code skipped for space */ } int distanceMoved = drive(); drive(); Object obj = drive(); if (checkGas(0.2) < checkGas(-0.1)) System.out.println("I think we have a problem"); checkGas(fillUp) = 1.0; Car tesla = getDreamCar(); if (getDreamCar().odometer > ) { System.out.println("I'll wait"); getDreamCar() = null; }
60
Local Variables Inside method, local variables can be declared
No defaults exist: must assign value before use "Die" when block completes; value not saved if run again Always declare local in smallest enclosing block Reduces chance of error & simplifies reading of code No time needed to create so program will be just as fast Compiler does this anyway, so no savings from skipping As an added bonus, debugging will be much simpler
61
Local Variable Key Concept
Add locals whenever they will make code readable (Compiler does this anyway!)
62
Methods' Parameters Each method can also declare parameters
Leave blank if no parameters wanted in method Like variables, parameters declared with name & type Parameters behave like variables scoped to method void bladder() { // Code skipped for space } short cash(byte loanShark) { // Code skipped } long johnSilver(Rum drinking, float boat) { // Code goes here, skipped for space }
63
Are Parameters Variables?
At start of method, assigned value of argument Works like normal assignment for the parameters type This means that primitives copied & references aliased Parameters "live" only during call & die once over Parameter placed in memory at top of frame on stack Variables also found in frame just at lower addresses
64
Are Parameters Variables?
At start of method, assigned value of argument Works like normal assignment for the parameters type This means that primitives copied & references aliased Parameters "live" only during call & die once over Parameter placed in memory at top of frame on stack Variables also found in frame just at lower addresses
65
Parameter like local which copies/aliases value passed in
Parameter Key Concept Parameter like local which copies/aliases value passed in
66
Best Choice of Variable
Does code calculate & use value inside single call? Use local variable & avoid bugs from using old values Value created outside, but used inside single call? Use parameter: value passed in, but limits reuse errors Does instance need value after method call ends? Use instance variable so that value remains available
67
Constructors Special methods called to instantiate object
Identical name as class; can have o or more parameters If signatures differ, multiple constructors possible No return type (not even void); issues occur if added Arguments to new must match class constructor When no constructor defined, implicit constructor used No parameters included in implicit constructor
68
Constructors Key Concept
A method with same name as class BUT NO RETURN TYPE
69
Every instance gets own copy of instance variables
Fields Key Concept #1 Every instance gets own copy of instance variables
70
Aliased variables see ALL changes to instance variables
Fields Key Concept #2 Aliased variables see ALL changes to instance variables
71
Fields Key Concept #3 Fields initialized to default value of 0, false, or null (almost all other variables need assignment before use)
72
return Statement Key Concept
73
Method Calling Key Concept #1
74
Method Calling Key Concept #2
Calls cannot be on left-hand side of assignment Ignore what we are using in the return statement. It is the VALUE of a field or variable that is returned, not the variable itself
75
Method Calling Key Concept #3
Can use result of method call just like any value (but this is bad style, so don't)
76
Parameter like local which copies/aliases value passed in
Parameter Key Concept Parameter like local which copies/aliases value passed in
77
Constructors Key Concept
A method with same name as class BUT NO RETURN TYPE
78
For Next Lecture Keep reviewing your Java lessons
Should be getting back up-to-speed with Java basics Friday will discuss how fields in an object work How to store values between calls to a method? There are weekly assignment problems to do Week #1 due next Thursday in week one special case Should help finish removing rust from lazy summer Enjoy long weekend; last break for several months Definitely needed after long, hard days of work
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.