SlideShare a Scribd company logo
1 of 17
How Objects Behavemethods use instance variables LIS4930 © PIC You already know that each instance of a class can have its own unique values for instance variables. Dog A can have a name “Rufus” and a weight of 70lbs. Dog B is “Killer” and weighs 9 pounds. And if the Dog class has a method makeNoise(), well, don’t you think a 70lb dog barks a bit deeper than the little 9-pounder? Rufus Killer Fortunately that is the whole point of an object – it has behavior that acts on its state. In other words, methods use instance variable values. Like, “if dog is less than 14lbs, make yippy sound, else…” or “increase weight by 5”.
How Objects Behave LIS4930 © PIC You already know that objects of one type can have different instance variable values. But what about the methods? Can every object of that type have different method behavior? Song title artist knows setTitle() setArtist() play() Sing Travis My Way Sex Pistols My Way Sinatra Sister DMB Politik Coldplay does t2 s3 Calling play() on this instance will cause “Sing” to play. Calling play() on this instance will cause “My Way” to play. But, not the Sinatra one! Song Song
The Size Affects the Bark! LIS4930 © PIC Dog name bark()
You Can Send Things To A Method LIS4930 © PIC Just as you may have done in other programming languages, you can pass values into your methods.  A method uses parameters. A caller passes arguments. Arguments are the things you pass into the methods. An argument lands face-down into a parameter. And a parameter is nothing more than a local variable. A variable with a type and a name, that can be used inside the body of the method. But here’s the important part: If a method takes a parameter, you MUST pass it something
LIS4930 © PIC Call the jump method on the Dog reference, and pass in the value 3 (as the argument to the method). 2 1 The bits representing the int value 3 are delivered into the bark method. argument parameter The bits land in the numOfJumps parameter (an int-sized variable). Use the numOfJumps parameter as a variable in the method code. 3 4 void jump (intnumOfJumps){ 		while (numOfJumps > 0) { //volunteer jumps once numOfJumps = numOfJumps – 1; 	}	 } Dog d = new Dog() d.jump(3);
You can get things back from a method LIS4930 © PIC Methods can return values. Every method is declared with a return type, but until now we’ve made all of our methods with a void return type, which means they don’t give anything back. void go() { } intgiveNumber () { 	return 42; } But, we can declare a method to give a specific type of value back to the caller, such as: If you declare a method to return a value, you must return a value of the declared type! (Or something that is compatible with the declared type!) Whatever you say you’ll give back, you better give back!
LIS4930 © PIC You can get things back from a method 00101010 theSecret These types MUST match The bits representing 42 are returned from the giveSecret() method, and land in the variable named theSecret. int intgiveSecret ( ){ intsecretNum = 42;		 	return secretNum;	 } inttheSecret = life.giveSecret( );
LIS4930 © PIC You Can Send MORE Than One Thing To A Method Methods can have multiple parameters. Separate them with commas ( , ) when you declare them, and separate the arguments with commas when you pass them.  Most importantly: The arguments you pass land in the same order you passed them. First argument lands in the first parameter, second argument in the second parameter, and so no. Calling a two-parameter method, and sending it two arguments: If a method has parameters, you must pass arguments of the right type and order. void go( ) { TestStufft = new TestStuff( ); t.takeTwo (12, 34); } void takeTwo( intx, inty ) { intz = x + y; System.out.println(“Total is “ + z); }
LIS4930 © PIC You Can Send MORE Than One Thing To A Method You can pass variables into a method, as long as the variable type matches the parameter type. What’s the value of z? It’s the same result you’d get if you divided snicker by bar at the time you passed them into the takeTwo method. The values of snicker and bar land in the x and y parameters. So now the bits in x are identical to the bits in foo (the bit pattern for the integer ‘7’) and the bits in y are identical to the bits in bar. void go( ) { int snicker = 8; int bar = 4; t.takeTwo(snicker, bar); } void takeTwo( intx, inty ) { x = 13; intz =x / y; System.out.println(“Resultis “ + z); }
Java is Pass-by-Value. That Means Pass-by-copy. LIS4930 © PIC 1 2 3 4 Declare an int variable and assign it the value ‘7’. The bit pattern for 7 goes into the variable named x. 00000111 intx = 7; X int Declare a method with an int parameter named z. Z void go(intz) { } int 00000111 00000111 Call the go() method, passing the variable x as the argument. The bits in x are copied, and the copy lands in z. Z copy of x X int int foo.go(x); void go (intz); x and z aren’t connected Change the value of z inside the method. The value of x doesn’t change! The argument passed to the z parameter was only a copy of x. The method can’t change the bits that were in the calling variable x.  00000111 0000000 X Z int int void go (intz) { z = 0; }
There are no Dumb Questions! LIS4930 © PIC Q: What happens if the argument you want to pass is an object instead of a primitive? A: Java passes everything by value. Everything. But value means bits inside the variable. And remember, you don’t stuff objects into variables; the variable is a remote control – a reference to an object. So if you pass a reference to an object into a method, you’re passing a copy of the remote control. Q: Do I have to return the exact type I declared? A: You can return anything that can be implicitly promoted to that type. But, you must use an explicit cast when the declared type is smaller than what you’re trying to return.
Getters & Setters LIS4930 © PIC Now that we’ve seen how parameters and return types work, it’s time to put them to good use: Getters and Setters. Getters and Setters are methods that get and set instance variables. A Getter’s sole purpose in life is to send back, as a return value, the value of whatever it is supposed to be Getting. ElectricGuitar brand numOfPickups rockStarUsesIt getBrand() setBrand() getNumOfPickups() setNumOfPickups() getRockStarUsesIt() setRockStarUsesIt() A Setter’s sole purpose is to take an argument value and use it to set the value of an instance variable.
ENCAPSULATIONCover Your Exposed Parts! LIS4930 © PIC Here we have been humming along without a care in the world leaving our data out there for anyone  to see and even touch. Exposed means reachable with the dot operator, as in: theCat.height = 7; Think about this idea of using our remote control to control the cat, and the remote getting into the hands of the wrong person. A reference variable (the remote) could be quite dangerous. Because what is to prevent: theCat.height = 40;
LIS4930 © PIC ENCAPSULATIONCover Your Exposed Parts! By forcing everybody to call a setter method, we can protect the cat from unacceptable size changes. We put in checks to guarantee a minimum cat height Cat name height color setName() getName() setHeight() getHeight() setColor()getColor() Encapsulation puts a fig leaf over the instance variables, so nobody can set them to something inappropriate. public void setHeight (int ht) { 	if (ht > 9) { 		height = ht; 	} }
Hide the Data LIS4930 © PIC OK so you now know how to protect your data (instance variables) but how do you hide them? You are already familiar with the public key word seen in every main() method; the public key word is called an access modifier and it allows anyone to access (call) that method. Well, there is another access modifier called private. Private only allows members of that very object to access its contents. So for instance, if the instance variables of an object are se to private only that object’s methods can access its instance variables! Here’s an encapsulation starter rule-of-thumb: Mark instance variables private. Mark getters and setters public.
Encapsulating the GoodDog Class LIS4930 © PIC Make the instance variable private Make the getter and setter methods public Even though the methods can’t really add new functionality, the cool thing is that you can change your mind later, You can come back and make a method safer, faster, better.
SUMMARY LIS4930 © PIC ALL variables must have: Access Modifier (optional) Type Name  Value (optional) private int kyle = 10; ALL methods must have: Access Modifier (optional) Return type Name  Parameters (optional) Curly brackets public void bark(int x) { }

More Related Content

What's hot

Pointers & References in C++
Pointers & References in C++Pointers & References in C++
Pointers & References in C++Ilio Catallo
 
Resource wrappers in C++
Resource wrappers in C++Resource wrappers in C++
Resource wrappers in C++Ilio Catallo
 
C programming - Pointers
C programming - PointersC programming - Pointers
C programming - PointersWingston
 
The Expression Problem - Part 2
The Expression Problem - Part 2The Expression Problem - Part 2
The Expression Problem - Part 2Philip Schwarz
 
Cplusplus
CplusplusCplusplus
Cplusplusdancey
 
Syntax Comparison of Golang with C and Java - Mindbowser
Syntax Comparison of Golang with C and Java - MindbowserSyntax Comparison of Golang with C and Java - Mindbowser
Syntax Comparison of Golang with C and Java - MindbowserMindbowser Inc
 
Learning C++ - Pointers in c++ 2
Learning C++ - Pointers in c++ 2Learning C++ - Pointers in c++ 2
Learning C++ - Pointers in c++ 2Ali Aminian
 
python Function
python Function python Function
python Function Ronak Rathi
 
Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)tech4us
 
Complex C-declarations & typedef
Complex C-declarations & typedefComplex C-declarations & typedef
Complex C-declarations & typedefSaurav Mukherjee
 
Inversion Theorem for Generalized Fractional Hilbert Transform
Inversion Theorem for Generalized Fractional Hilbert TransformInversion Theorem for Generalized Fractional Hilbert Transform
Inversion Theorem for Generalized Fractional Hilbert Transforminventionjournals
 

What's hot (19)

Pointer
PointerPointer
Pointer
 
Pointers & References in C++
Pointers & References in C++Pointers & References in C++
Pointers & References in C++
 
This pointer
This pointerThis pointer
This pointer
 
Resource wrappers in C++
Resource wrappers in C++Resource wrappers in C++
Resource wrappers in C++
 
C programming - Pointers
C programming - PointersC programming - Pointers
C programming - Pointers
 
Computer Programming- Lecture 5
Computer Programming- Lecture 5 Computer Programming- Lecture 5
Computer Programming- Lecture 5
 
The Expression Problem - Part 2
The Expression Problem - Part 2The Expression Problem - Part 2
The Expression Problem - Part 2
 
Cplusplus
CplusplusCplusplus
Cplusplus
 
Pointers in c++ by minal
Pointers in c++ by minalPointers in c++ by minal
Pointers in c++ by minal
 
Syntax Comparison of Golang with C and Java - Mindbowser
Syntax Comparison of Golang with C and Java - MindbowserSyntax Comparison of Golang with C and Java - Mindbowser
Syntax Comparison of Golang with C and Java - Mindbowser
 
LectureNotes-04-DSA
LectureNotes-04-DSALectureNotes-04-DSA
LectureNotes-04-DSA
 
Learning C++ - Pointers in c++ 2
Learning C++ - Pointers in c++ 2Learning C++ - Pointers in c++ 2
Learning C++ - Pointers in c++ 2
 
python Function
python Function python Function
python Function
 
Clojure basics
Clojure basicsClojure basics
Clojure basics
 
Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)
 
Complex C-declarations & typedef
Complex C-declarations & typedefComplex C-declarations & typedef
Complex C-declarations & typedef
 
Strings v.1.1
Strings v.1.1Strings v.1.1
Strings v.1.1
 
Computer programming 2 Lesson 10
Computer programming 2  Lesson 10Computer programming 2  Lesson 10
Computer programming 2 Lesson 10
 
Inversion Theorem for Generalized Fractional Hilbert Transform
Inversion Theorem for Generalized Fractional Hilbert TransformInversion Theorem for Generalized Fractional Hilbert Transform
Inversion Theorem for Generalized Fractional Hilbert Transform
 

Viewers also liked (19)

Javascript2
Javascript2Javascript2
Javascript2
 
15b more gui
15b more gui15b more gui
15b more gui
 
8 Typography Notes
8 Typography Notes8 Typography Notes
8 Typography Notes
 
Html5
Html5Html5
Html5
 
Chapter.10
Chapter.10Chapter.10
Chapter.10
 
09 polymorphism
09 polymorphism09 polymorphism
09 polymorphism
 
Web architecture
Web architectureWeb architecture
Web architecture
 
13 interfaces
13 interfaces13 interfaces
13 interfaces
 
02 prepcode
02 prepcode02 prepcode
02 prepcode
 
CGS2835 HTML5
CGS2835 HTML5CGS2835 HTML5
CGS2835 HTML5
 
13 life and scope
13 life and scope13 life and scope
13 life and scope
 
Web architecture
Web architectureWeb architecture
Web architecture
 
Mysocial databasequeries
Mysocial databasequeriesMysocial databasequeries
Mysocial databasequeries
 
Mysocial databasequeries
Mysocial databasequeriesMysocial databasequeries
Mysocial databasequeries
 
6. Page Structure
6. Page Structure6. Page Structure
6. Page Structure
 
4 Interface Design
4 Interface Design4 Interface Design
4 Interface Design
 
Javascript
JavascriptJavascript
Javascript
 
Chapter.04
Chapter.04Chapter.04
Chapter.04
 
Chapter.02
Chapter.02Chapter.02
Chapter.02
 

Similar to How Objects Use Instance Variables in Methods

Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]Palak Sanghani
 
Pointers, virtual function and polymorphism
Pointers, virtual function and polymorphismPointers, virtual function and polymorphism
Pointers, virtual function and polymorphismlalithambiga kamaraj
 
Using-Python-Libraries.9485146.powerpoint.pptx
Using-Python-Libraries.9485146.powerpoint.pptxUsing-Python-Libraries.9485146.powerpoint.pptx
Using-Python-Libraries.9485146.powerpoint.pptxUadAccount
 
C++ Course - Lesson 3
C++ Course - Lesson 3C++ Course - Lesson 3
C++ Course - Lesson 3Mohamed Ahmed
 
vectors.(join ALL INDIA POLYTECHNIC (AICTE)).pptx
vectors.(join ALL INDIA POLYTECHNIC (AICTE)).pptxvectors.(join ALL INDIA POLYTECHNIC (AICTE)).pptx
vectors.(join ALL INDIA POLYTECHNIC (AICTE)).pptxVivekSharma34623
 
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docxISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docxpriestmanmable
 
Lesson 17. Pattern 9. Mixed arithmetic
Lesson 17. Pattern 9. Mixed arithmeticLesson 17. Pattern 9. Mixed arithmetic
Lesson 17. Pattern 9. Mixed arithmeticPVS-Studio
 
Anton Kasyanov, Introduction to Python, Lecture2
Anton Kasyanov, Introduction to Python, Lecture2Anton Kasyanov, Introduction to Python, Lecture2
Anton Kasyanov, Introduction to Python, Lecture2Anton Kasyanov
 
pointer, virtual function and polymorphism
pointer, virtual function and polymorphismpointer, virtual function and polymorphism
pointer, virtual function and polymorphismramya marichamy
 
C++ Course - Lesson 2
C++ Course - Lesson 2C++ Course - Lesson 2
C++ Course - Lesson 2Mohamed Ahmed
 
1_Python Basics.pdf
1_Python Basics.pdf1_Python Basics.pdf
1_Python Basics.pdfMaheshGour5
 
Lec 9 05_sept [compatibility mode]
Lec 9 05_sept [compatibility mode]Lec 9 05_sept [compatibility mode]
Lec 9 05_sept [compatibility mode]Palak Sanghani
 
03 Variables - Chang.pptx
03 Variables - Chang.pptx03 Variables - Chang.pptx
03 Variables - Chang.pptxDileep804402
 
Csharp4 operators and_casts
Csharp4 operators and_castsCsharp4 operators and_casts
Csharp4 operators and_castsAbed Bukhari
 
Complicated declarations in c
Complicated declarations in cComplicated declarations in c
Complicated declarations in cRahul Budholiya
 

Similar to How Objects Use Instance Variables in Methods (20)

04 Variables
04 Variables04 Variables
04 Variables
 
l7-pointers.ppt
l7-pointers.pptl7-pointers.ppt
l7-pointers.ppt
 
Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]
 
Python basics
Python basicsPython basics
Python basics
 
Pointers, virtual function and polymorphism
Pointers, virtual function and polymorphismPointers, virtual function and polymorphism
Pointers, virtual function and polymorphism
 
Using-Python-Libraries.9485146.powerpoint.pptx
Using-Python-Libraries.9485146.powerpoint.pptxUsing-Python-Libraries.9485146.powerpoint.pptx
Using-Python-Libraries.9485146.powerpoint.pptx
 
C++ Course - Lesson 3
C++ Course - Lesson 3C++ Course - Lesson 3
C++ Course - Lesson 3
 
vectors.(join ALL INDIA POLYTECHNIC (AICTE)).pptx
vectors.(join ALL INDIA POLYTECHNIC (AICTE)).pptxvectors.(join ALL INDIA POLYTECHNIC (AICTE)).pptx
vectors.(join ALL INDIA POLYTECHNIC (AICTE)).pptx
 
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docxISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
 
Lesson 17. Pattern 9. Mixed arithmetic
Lesson 17. Pattern 9. Mixed arithmeticLesson 17. Pattern 9. Mixed arithmetic
Lesson 17. Pattern 9. Mixed arithmetic
 
C Programming - Refresher - Part III
C Programming - Refresher - Part IIIC Programming - Refresher - Part III
C Programming - Refresher - Part III
 
Anton Kasyanov, Introduction to Python, Lecture2
Anton Kasyanov, Introduction to Python, Lecture2Anton Kasyanov, Introduction to Python, Lecture2
Anton Kasyanov, Introduction to Python, Lecture2
 
pointer, virtual function and polymorphism
pointer, virtual function and polymorphismpointer, virtual function and polymorphism
pointer, virtual function and polymorphism
 
C++ Course - Lesson 2
C++ Course - Lesson 2C++ Course - Lesson 2
C++ Course - Lesson 2
 
1_Python Basics.pdf
1_Python Basics.pdf1_Python Basics.pdf
1_Python Basics.pdf
 
Lec 9 05_sept [compatibility mode]
Lec 9 05_sept [compatibility mode]Lec 9 05_sept [compatibility mode]
Lec 9 05_sept [compatibility mode]
 
03 Variables - Chang.pptx
03 Variables - Chang.pptx03 Variables - Chang.pptx
03 Variables - Chang.pptx
 
Csharp4 operators and_casts
Csharp4 operators and_castsCsharp4 operators and_casts
Csharp4 operators and_casts
 
Complicated declarations in c
Complicated declarations in cComplicated declarations in c
Complicated declarations in c
 
06a methods original
06a methods original06a methods original
06a methods original
 

More from Program in Interdisciplinary Computing (20)

Phpmysqlcoding
PhpmysqlcodingPhpmysqlcoding
Phpmysqlcoding
 
Database basics
Database basicsDatabase basics
Database basics
 
CGS2835 HTML5
CGS2835 HTML5CGS2835 HTML5
CGS2835 HTML5
 
01 intro tousingjava
01 intro tousingjava01 intro tousingjava
01 intro tousingjava
 
Web architecture v3
Web architecture v3Web architecture v3
Web architecture v3
 
Xhtml
XhtmlXhtml
Xhtml
 
Webdev
WebdevWebdev
Webdev
 
Sdlc
SdlcSdlc
Sdlc
 
Mysocial
MysocialMysocial
Mysocial
 
Javascript
JavascriptJavascript
Javascript
 
Frameworks
FrameworksFrameworks
Frameworks
 
Drupal
DrupalDrupal
Drupal
 
Database
DatabaseDatabase
Database
 
12 abstract classes
12 abstract classes12 abstract classes
12 abstract classes
 
11 polymorphism
11 polymorphism11 polymorphism
11 polymorphism
 
15a gui
15a gui15a gui
15a gui
 
14b exceptions
14b exceptions14b exceptions
14b exceptions
 
14a exceptions
14a exceptions14a exceptions
14a exceptions
 
11 interfaces
11 interfaces11 interfaces
11 interfaces
 
10 abstract
10 abstract10 abstract
10 abstract
 

How Objects Use Instance Variables in Methods

  • 1. How Objects Behavemethods use instance variables LIS4930 © PIC You already know that each instance of a class can have its own unique values for instance variables. Dog A can have a name “Rufus” and a weight of 70lbs. Dog B is “Killer” and weighs 9 pounds. And if the Dog class has a method makeNoise(), well, don’t you think a 70lb dog barks a bit deeper than the little 9-pounder? Rufus Killer Fortunately that is the whole point of an object – it has behavior that acts on its state. In other words, methods use instance variable values. Like, “if dog is less than 14lbs, make yippy sound, else…” or “increase weight by 5”.
  • 2. How Objects Behave LIS4930 © PIC You already know that objects of one type can have different instance variable values. But what about the methods? Can every object of that type have different method behavior? Song title artist knows setTitle() setArtist() play() Sing Travis My Way Sex Pistols My Way Sinatra Sister DMB Politik Coldplay does t2 s3 Calling play() on this instance will cause “Sing” to play. Calling play() on this instance will cause “My Way” to play. But, not the Sinatra one! Song Song
  • 3. The Size Affects the Bark! LIS4930 © PIC Dog name bark()
  • 4. You Can Send Things To A Method LIS4930 © PIC Just as you may have done in other programming languages, you can pass values into your methods. A method uses parameters. A caller passes arguments. Arguments are the things you pass into the methods. An argument lands face-down into a parameter. And a parameter is nothing more than a local variable. A variable with a type and a name, that can be used inside the body of the method. But here’s the important part: If a method takes a parameter, you MUST pass it something
  • 5. LIS4930 © PIC Call the jump method on the Dog reference, and pass in the value 3 (as the argument to the method). 2 1 The bits representing the int value 3 are delivered into the bark method. argument parameter The bits land in the numOfJumps parameter (an int-sized variable). Use the numOfJumps parameter as a variable in the method code. 3 4 void jump (intnumOfJumps){ while (numOfJumps > 0) { //volunteer jumps once numOfJumps = numOfJumps – 1; } } Dog d = new Dog() d.jump(3);
  • 6. You can get things back from a method LIS4930 © PIC Methods can return values. Every method is declared with a return type, but until now we’ve made all of our methods with a void return type, which means they don’t give anything back. void go() { } intgiveNumber () { return 42; } But, we can declare a method to give a specific type of value back to the caller, such as: If you declare a method to return a value, you must return a value of the declared type! (Or something that is compatible with the declared type!) Whatever you say you’ll give back, you better give back!
  • 7. LIS4930 © PIC You can get things back from a method 00101010 theSecret These types MUST match The bits representing 42 are returned from the giveSecret() method, and land in the variable named theSecret. int intgiveSecret ( ){ intsecretNum = 42; return secretNum; } inttheSecret = life.giveSecret( );
  • 8. LIS4930 © PIC You Can Send MORE Than One Thing To A Method Methods can have multiple parameters. Separate them with commas ( , ) when you declare them, and separate the arguments with commas when you pass them. Most importantly: The arguments you pass land in the same order you passed them. First argument lands in the first parameter, second argument in the second parameter, and so no. Calling a two-parameter method, and sending it two arguments: If a method has parameters, you must pass arguments of the right type and order. void go( ) { TestStufft = new TestStuff( ); t.takeTwo (12, 34); } void takeTwo( intx, inty ) { intz = x + y; System.out.println(“Total is “ + z); }
  • 9. LIS4930 © PIC You Can Send MORE Than One Thing To A Method You can pass variables into a method, as long as the variable type matches the parameter type. What’s the value of z? It’s the same result you’d get if you divided snicker by bar at the time you passed them into the takeTwo method. The values of snicker and bar land in the x and y parameters. So now the bits in x are identical to the bits in foo (the bit pattern for the integer ‘7’) and the bits in y are identical to the bits in bar. void go( ) { int snicker = 8; int bar = 4; t.takeTwo(snicker, bar); } void takeTwo( intx, inty ) { x = 13; intz =x / y; System.out.println(“Resultis “ + z); }
  • 10. Java is Pass-by-Value. That Means Pass-by-copy. LIS4930 © PIC 1 2 3 4 Declare an int variable and assign it the value ‘7’. The bit pattern for 7 goes into the variable named x. 00000111 intx = 7; X int Declare a method with an int parameter named z. Z void go(intz) { } int 00000111 00000111 Call the go() method, passing the variable x as the argument. The bits in x are copied, and the copy lands in z. Z copy of x X int int foo.go(x); void go (intz); x and z aren’t connected Change the value of z inside the method. The value of x doesn’t change! The argument passed to the z parameter was only a copy of x. The method can’t change the bits that were in the calling variable x. 00000111 0000000 X Z int int void go (intz) { z = 0; }
  • 11. There are no Dumb Questions! LIS4930 © PIC Q: What happens if the argument you want to pass is an object instead of a primitive? A: Java passes everything by value. Everything. But value means bits inside the variable. And remember, you don’t stuff objects into variables; the variable is a remote control – a reference to an object. So if you pass a reference to an object into a method, you’re passing a copy of the remote control. Q: Do I have to return the exact type I declared? A: You can return anything that can be implicitly promoted to that type. But, you must use an explicit cast when the declared type is smaller than what you’re trying to return.
  • 12. Getters & Setters LIS4930 © PIC Now that we’ve seen how parameters and return types work, it’s time to put them to good use: Getters and Setters. Getters and Setters are methods that get and set instance variables. A Getter’s sole purpose in life is to send back, as a return value, the value of whatever it is supposed to be Getting. ElectricGuitar brand numOfPickups rockStarUsesIt getBrand() setBrand() getNumOfPickups() setNumOfPickups() getRockStarUsesIt() setRockStarUsesIt() A Setter’s sole purpose is to take an argument value and use it to set the value of an instance variable.
  • 13. ENCAPSULATIONCover Your Exposed Parts! LIS4930 © PIC Here we have been humming along without a care in the world leaving our data out there for anyone to see and even touch. Exposed means reachable with the dot operator, as in: theCat.height = 7; Think about this idea of using our remote control to control the cat, and the remote getting into the hands of the wrong person. A reference variable (the remote) could be quite dangerous. Because what is to prevent: theCat.height = 40;
  • 14. LIS4930 © PIC ENCAPSULATIONCover Your Exposed Parts! By forcing everybody to call a setter method, we can protect the cat from unacceptable size changes. We put in checks to guarantee a minimum cat height Cat name height color setName() getName() setHeight() getHeight() setColor()getColor() Encapsulation puts a fig leaf over the instance variables, so nobody can set them to something inappropriate. public void setHeight (int ht) { if (ht > 9) { height = ht; } }
  • 15. Hide the Data LIS4930 © PIC OK so you now know how to protect your data (instance variables) but how do you hide them? You are already familiar with the public key word seen in every main() method; the public key word is called an access modifier and it allows anyone to access (call) that method. Well, there is another access modifier called private. Private only allows members of that very object to access its contents. So for instance, if the instance variables of an object are se to private only that object’s methods can access its instance variables! Here’s an encapsulation starter rule-of-thumb: Mark instance variables private. Mark getters and setters public.
  • 16. Encapsulating the GoodDog Class LIS4930 © PIC Make the instance variable private Make the getter and setter methods public Even though the methods can’t really add new functionality, the cool thing is that you can change your mind later, You can come back and make a method safer, faster, better.
  • 17. SUMMARY LIS4930 © PIC ALL variables must have: Access Modifier (optional) Type Name Value (optional) private int kyle = 10; ALL methods must have: Access Modifier (optional) Return type Name Parameters (optional) Curly brackets public void bark(int x) { }

Editor's Notes

  1. http://www.google.com/search?hl=en&client=firefox-a&rls=org.mozilla%3Aen-US%3Aofficial&hs=QUE&q=the+answer+to+life+the+universe+and+everything&btnG=Search&aq=f&oq=&aqi=g10