How to Return Without Running Method Again Java
Chapter 4. Methods Employ Example Variables: How Objects Carry
State affects beliefs, behavior affects state. We know that objects have state and behavior , represented by instance variables and methods . But until now, nosotros haven't looked at how state and beliefs are related . We already know that each instance of a form (each object of a particular type) can have its ain unique values for its example variables. Domestic dog A can have a proper name "Fido" and a weight of seventy pounds. Dog B is "Killer" and weighs ix pounds. And if the Dog form has a method makeNoise(), well, don't y'all think a 70-pound domestic dog barks a fleck deeper than the piddling nine-pounder? (Assuming that abrasive yippy sound can exist considered a bawl .) Fortunately, that'south the whole point of an object—it has beliefs that acts on its state . In other words, methods utilise case variable values . Similar, "if dog is less than 14 pounds, brand yippy sound, else..." or "increase weight by 5". Let's go change some country.
Remember: a course describes what an object knows and what an object does
A class is the blueprint for an object. When you write a class, you're describing how the JVM should make an object of that type. You already know that every object of that type tin have dissimilar instance variable values. But what most the methods?
Can every object of that type have dissimilar method behavior?
Well... sort of. *
Every example of a detail class has the aforementioned methods, but the methods can deport differently based on the value of the example variables.
The Song class has two case variables, title and creative person . The play() method plays a song, but the case you telephone call play() on will play the song represented by the value of the championship instance variable for that instance. So, if you phone call the play() method on one instance yous'll hear the song "Politik", while another instance plays "Darkstar". The method code, however, is the same.
void play() { soundPlayer.playSound(title); }
Song t2 = new Song(); t2.setArtist("Travis"); t2.setTitle("Sing"); Song s3 = new Song(); s3.setArtist("Sex Pistols"); s3.setTitle("My Manner");
The size affects the bark
A small Dog'south bawl is different from a large Dog'due south bark.
The Dog class has an instance variable size , that the bark() method uses to decide what kind of bark sound to make.
You can send things to a method
Just equally you expect from any programming language, you tin can pass values into your methods. Y'all might, for example, want to tell a Dog object how many times to bawl by calling:
d.bark(three); Depending on your programming background and personal preferences, you might utilize the term arguments or perhaps parameters for the values passed into a method. Although there are formal information science distinctions that people who article of clothing lab coats and who volition almost certainly not read this book, make, we have bigger fish to fry in this volume. So you can call them whatsoever y'all like (arguments, donuts, hairballs, etc.) but we're doing it like this:
A method uses parameters. A caller passes arguments.
Arguments are the things yous laissez passer into the methods. An statement (a value like ii, "Foo", or a reference to a Domestic dog) lands face up-down into a... wait for information technology... parameter . And a parameter is nothing more than a local variable. A variable with a type and a name, that tin can be used inside the body of the method.
Just here'south the important part: If a method takes a parameter, you must pass information technology something. And that something must be a value of the appropriate type.
You can become things dorsum from a method
Methods can return values. Every method is declared with a render type, but until at present nosotros've made all of our methods with a void return type, which means they don't give anything back.
void go() { }
But we can declare a method to give a specific type of value dorsum to the caller, such as:
int giveSecret() { return 42; }
If y'all declare a method to return a value, you must return a value of the alleged type! (Or a value that is compatible with the declared blazon. We'll become into that more when nosotros talk about polymorphism in Chapter 7 and Affiliate 8.)
Whatsoever you say you lot'll give back, you better give dorsum!
Annotation
The bits representing 42 are returned from the giveSecret() method, and land in the variable named theSecret.
You can send more than than one thing to a method
Methods can accept multiple parameters. Separate them with commas when yous declare them, and separate the arguments with commas when yous pass them. Most chiefly, if a method has parameters, you must laissez passer arguments of the correct type and order.
Calling a 2-parameter method, and sending it two arguments
You tin pass variables into a method, as long as the variable type matches the parameter type
Coffee is pass-by-value. That ways pass-by-copy
-
Declare an int variable and assign it the value '7'. The bit blueprint for 7 goes into the variable named x.
-
Declare a method with an int parameter named z.
-
Call the go() method, passing the variable 10 every bit the statement. The bits in x are copied, and the copy lands in z.
-
Change the value of z inside the method. The value of ten doesn't change! The statement passed to the z parameter was only a re-create of 10.
The method can't change the bits that were in the calling variable 10.
Note
Reminder: Java cares well-nigh blazon!
You can't return a Giraffe when the return blazon is declared as a Rabbit. Same thing with parameters. You can't pass a Giraffe into a method that takes a Rabbit.
Absurd things you tin do with parameters and return types
At present that we've seen how parameters and return types work, information technology's time to put them to good apply: Getters and Setters . If you're into being all formal about it, you might adopt to call them Accessors and Mutators . But that's a waste of perfectly good syllables. Likewise, Getters and Setters fits the Java naming convention, so that's what we'll telephone call them.
Getters and Setters allow you, well, get and set things . Instance variable values, usually. A Getter's sole purpose in life is to send back, as a return value, the value of whatever it is that particular Getter is supposed to be Getting. And by now, it's probably no surprise that a Setter lives and breathes for the gamble to take an argument value and use it to set the value of an instance variable.
class ElectricGuitar { String brand; int numOfPickups; boolean rockStarUsesIt; Cord getBrand() { return brand; } void setBrand(String aBrand) { brand = aBrand; } int getNumOfPickups() { return numOfPickups; } void setNumOfPickups(int num) { numOfPickups = num; } boolean getRockStarUsesIt() { return rockStarUsesIt; } void setRockStarUsesIt(boolean yesOrNo) { rockStarUsesIt = yesOrNo; } }
Encapsulation
Do information technology or risk humiliation and ridicule
Until this near important moment, we've been committing one of the worst OO simulated pas (and we're not talking modest violation like showing upwardly without the 'B' in BYOB). No, nosotros're talking Faux Pas with a majuscule 'F'. And 'P'.
Our shameful transgression?
Exposing our information!
Hither we are, only humming along without a care in the world leaving our data out there for anyone to run into and even affect.
You may have already experienced that vaguely unsettling feeling that comes with leaving your instance variables exposed.
Exposed ways reachable with the dot operator, as in:
theCat.height = 27; Think about this idea of using our remote control to make a straight change to the Cat object's size case variable. In the hands of the wrong person, a reference variable (remote control) is quite a dangerous weapon. Because what'due south to foreclose:
This would exist a Bad Thing. We demand to build setter methods for all the instance variables, and find a way to force other code to phone call the setters rather than access the data directly.
Note
By forcing everybody to telephone call a setter method, we can protect the cat from unacceptable size changes.
Hibernate the data
Yes it is that simple to go from an implementation that'southward but begging for bad information to one that protects your data and protects your right to alter your implementation later.
OK, so how exactly do you hibernate the data? With the public and private access modifiers. You're familiar with public –we use it with every main method.
Here's an encapsulation starter rule of thumb (all standard disclaimers about rules of thumb are in effect): mark your instance variables private and provide public getters and setters for access control. When you take more design and coding savvy in Java, you will probably exercise things a little differently, simply for now, this approach will keep you safe.
Note
Mark instance variables private.
Mark getters and setters public.
"Sadly, Bill forgot to encapsulate his Cat class and ended upward with a flat true cat."
(overheard at the water libation).
Encapsulating the GoodDog form
Note
Even though the methods don't actually add new functionality, the cool thing is that you can change your mind afterward. you can come dorsum and make a method safer, faster, meliorate.
Note
Any place where a item value can be used, a method call that returns that type can be used.
instead of:
int x = 3 + 24;
y'all can say:
int 10 = 3 + one.getSize();
How do objects in an array behave?
Just similar any other object. The only difference is how yous become to them. In other words, how you go the remote control. Allow'south try calling methods on Dog objects in an array.
-
Declare and create a Domestic dog array, to concur 7 Domestic dog references.
Dog[] pets; pets = new Canis familiaris[7];
-
Create two new Dog objects, and assign them to the first two array elements.
pets[0] = new Dog(); pets[i] = new Domestic dog();
-
Call methods on the 2 Domestic dog objects.
pets[0].setSize(30); int x = pets[0].getSize(); pets[1].setSize(8);
Declaring and initializing example variables
You lot already know that a variable declaration needs at to the lowest degree a proper name and a type:
int size; Cord proper name;
And you know that you can initialize (assign a value) to the variable at the same fourth dimension:
int size = 420; Cord name = "Donny";
But when you don't initialize an case variable, what happens when you phone call a getter method? In other words, what is the value of an example variable before you initialize it?
Note
Case variables always get a default value. If y'all don't explicitly assign a value to an instance variable, or you don't call a setter method, the instance variable however has a value!
| integers | 0 |
| floating points | 0.0 |
| booleans | fake |
| references | null |
Note
You don't have to initialize instance variables, considering they always have a default value. Number primitives (including char) become 0, booleans get false, and object reference variables get null.
(Recall, null merely means a remote control that isn't controlling / programmed to anything. A reference, but no actual object.)
The deviation between instance and local variables
-
Instance variables are declared within a class but not within a method.
class Equus caballus { private double height = 15.ii; private String breed; // more code... } -
Local variables are declared within a method.
form AddThing { int a; int b = 12; public int add() { int total = a + b; return full; } } -
Local variables MUST exist initialized before apply!
Local variables practice Non get a default value! The compiler complains if you try to employ a local variable before the variable is initialized.
Comparing variables (primitives or references)
Sometimes you want to know if ii primitives are the same. That'due south easy enough, just employ the == operator. Sometimes yous want to know if two reference variables refer to a single object on the heap. Easy as well, just utilize the == operator. Just sometimes y'all desire to know if ii objects are equal. And for that, you lot demand the .equals() method. The idea of equality for objects depends on the blazon of object. For instance, if two dissimilar Cord objects have the same characters (say, "expeditious"), they are meaningfully equivalent, regardless of whether they are two distinct objects on the heap. Only what almost a Domestic dog? Do you lot want to treat ii Dogs as being equal if they happen to have the same size and weight? Probably not. So whether two unlike objects should exist treated as equal depends on what makes sense for that particular object type. We'll explore the notion of object equality again in subsequently chapters (and Appendix B), but for now, we need to understand that the == operator is used only to compare the bits in two variables. What those bits stand for doesn't thing. The $.25 are either the same, or they're not.
Note
Utilize == to compare two primitives, or to encounter if two references refer to the same object.
Use the equals() method to run across if two dissimilar objects are equal.
(Such as 2 different String objects that both represent the characters in "Fred")
To compare two primitives, employ the == operator
The == operator can be used to compare two variables of whatsoever kind, and information technology but compares the $.25.
if (a == b) {...} looks at the $.25 in a and b and returns true if the bit pattern is the same (although it doesn't intendance about the size of the variable, and so all the extra zeroes on the left end don't affair).
int a = three; byte b = three; if (a == b) { // truthful }
To meet if two references are the same (which means they refer to the same object on the heap) employ the == operator
Remember, the == operator cares just about the pattern of bits in the variable. The rules are the same whether the variable is a reference or archaic. So the == operator returns truthful if two reference variables refer to the same object! In that example, we don't know what the scrap pattern is (because it's dependent on the JVM, and subconscious from united states) but we practice know that whatever it looks like, information technology will be the same for two references to a single object .
Foo a = new Foo(); Foo b = new Foo(); Foo c = a; if (a == b) { // imitation } if (a == c) { // true } if (b == c) { // false }
Source: https://www.oreilly.com/library/view/head-first-java/0596009208/ch04.html
0 Response to "How to Return Without Running Method Again Java"
Post a Comment