When Check if Method True the Method Is Called Again

Affiliate 4. Methods Utilize Instance Variables: How Objects Carry

image with no caption

State affects beliefs, behavior affects country. We know that objects have state and behavior , represented by instance variables and methods . Just until at present, we haven't looked at how land and behavior are related . We already know that each instance of a class (each object of a item type) can accept its own unique values for its case variables. Domestic dog A can have a proper name "Fido" and a weight of 70 pounds. Canis familiaris B is "Killer" and weighs 9 pounds. And if the Dog grade has a method makeNoise(), well, don't y'all recall a 70-pound domestic dog barks a fleck deeper than the little 9-pounder? (Bold that annoying yippy sound can exist considered a bawl .) Fortunately, that's the whole point of an object—it has behavior that acts on its state . In other words, methods utilize example variable values . Similar, "if dog is less than 14 pounds, make yippy sound, else..." or "increase weight by v". Let's become change some state.

Remember: a class describes what an object knows and what an object does

A class is the blueprint for an object. When yous write a class, you're describing how the JVM should make an object of that blazon. You lot already know that every object of that blazon can take dissimilar instance variable values. But what almost the methods?

image with no caption

Tin can every object of that type have different method beliefs?

Well... sort of. *

Every example of a detail grade has the same methods, just the methods tin behave differently based on the value of the case variables.

The Song course has two case variables, title and artist . The play() method plays a song, merely the instance you call play() on will play the song represented by the value of the championship instance variable for that example. Then, if you lot call the play() method on one instance you lot'll hear the song "Politik", while another instance plays "Darkstar". The method lawmaking, however, is the same.

                              void play() {                                            soundPlayer.playSound(title);                                            }                          

image with no caption

                              Vocal t2 = new Song();                                            t2.setArtist("Travis");                                            t2.setTitle("Sing");                                            Song s3 = new Song();                                            s3.setArtist("Sex activity Pistols");                                            s3.setTitle("My Way");                          

The size affects the bawl

A pocket-size Dog's bawl is different from a large Dog'south bawl.

The Dog grade has an instance variable size , that the bark() method uses to decide what kind of bark sound to brand.

image with no caption

image with no caption

image with no caption

Yous can ship things to a method

Just as y'all expect from whatever programming linguistic communication, you can pass values into your methods. You lot might, for instance, want to tell a Dog object how many times to bawl by calling:

                          d.bark(3);                      

Depending on your programming groundwork and personal preferences, y'all might use the term arguments or peradventure parameters for the values passed into a method. Although there are formal computer science distinctions that people who wear lab coats and who will almost certainly not read this book, make, nosotros take bigger fish to fry in this book. And so you can call them whatever you lot similar (arguments, donuts, hairballs, etc.) just we're doing it like this:

A method uses parameters. A caller passes arguments.

Arguments are the things you pass into the methods. An argument (a value similar ii, "Foo", or a reference to a Canis familiaris) lands face up-down into a... expect for it... parameter . And a parameter is nothing more than than a local variable. A variable with a blazon and a name, that can be used inside the body of the method.

But here'due south the important office: If a method takes a parameter, you must laissez passer it something. And that something must be a value of the appropriate blazon.

image with no caption

You tin get things back from a method

Methods tin can return values. Every method is declared with a return type, simply until now we've made all of our methods with a void return type, which means they don't give anything back.

                          void get() {                                      }                      

But we can declare a method to requite a specific type of value back to the caller, such equally:

                          int giveSecret() {                                      return 42;                                      }                      

If you declare a method to render a value, you must render a value of the declared type! (Or a value that is compatible with the declared blazon. We'll get into that more than when we talk about polymorphism in Chapter 7 and Chapter 8.)

Whatsoever you say you'll give back, y'all better give back!

image with no caption

Notation

The bits representing 42 are returned from the giveSecret() method, and land in the variable named theSecret.

You tin can send more than 1 thing to a method

Methods can have multiple parameters. Split them with commas when you declare them, and split up the arguments with commas when you pass them. Most chiefly, if a method has parameters, you must pass arguments of the correct type and gild.

Calling a two-parameter method, and sending it two arguments

image with no caption

You can pass variables into a method, every bit long as the variable type matches the parameter type

image with no caption

Java is laissez passer-by-value. That means pass-past-copy

image with no caption

  1. Declare an int variable and assign it the value '7'. The scrap pattern for vii goes into the variable named x.

    image with no caption

  2. Declare a method with an int parameter named z.

    image with no caption

  3. Call the become() method, passing the variable x as the statement. The bits in x are copied, and the copy lands in z.

    image with no caption

  4. Alter the value of z within the method. The value of ten doesn't modify! The statement passed to the z parameter was only a re-create of x.

    The method can't modify the $.25 that were in the calling variable x.

    image with no caption

Annotation

image with no caption

Reminder: Java cares about type!

Yous tin't render a Giraffe when the render type is alleged every bit a Rabbit. Aforementioned thing with parameters. You can't pass a Giraffe into a method that takes a Rabbit.

Cool things you can exercise with parameters and return types

Now that we've seen how parameters and return types work, it'due south time to put them to proficient utilise: Getters and Setters . If you're into being all formal nearly it, you lot might prefer to phone call them Accessors and Mutators . But that'south a waste of perfectly good syllables. Besides, Getters and Setters fits the Java naming convention, and then that's what we'll call them.

Getters and Setters allow yous, well, get and set things . Instance variable values, commonly. A Getter'southward sole purpose in life is to ship back, as a render value, the value of any it is that particular Getter is supposed to exist Getting. And by now, it's probably no surprise that a Setter lives and breathes for the take chances to take an argument value and utilise it to gear up the value of an example variable.

image with no caption

                          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;                                      }                                      }                      

image with no caption

Encapsulation

Do information technology or chance humiliation and ridicule

Until this most important moment, we've been committing one of the worst OO faux pas (and nosotros're not talking minor violation like showing up without the 'B' in BYOB). No, we're talking Faux Pas with a capital 'F'. And 'P'.

Our shameful transgression?

Exposing our information!

Here nosotros are, simply bustling along without a care in the globe leaving our data out there for anyone to come across and even touch.

image with no caption

You may have already experienced that vaguely unsettling feeling that comes with leaving your example variables exposed.

Exposed means reachable with the dot operator, as in:

                              theCat.elevation = 27;                          

Think about this idea of using our remote control to brand a straight change to the True cat object'south size instance variable. In the hands of the wrong person, a reference variable (remote control) is quite a dangerous weapon. Because what'due south to prevent:

image with no caption

This would exist a Bad Matter. We need to build setter methods for all the instance variables, and find a manner to force other lawmaking to call the setters rather than access the data direct.

Annotation

By forcing everybody to call a setter method, we can protect the cat from unacceptable size changes.

image with no caption

Hibernate the data

Aye it is that simple to go from an implementation that'southward merely begging for bad information to one that protects your data and protects your correct to modify your implementation later.

OK, then how exactly do yous hibernate the data? With the public and private access modifiers. Yous're familiar with public –nosotros apply it with every chief method.

Here's an encapsulation starter rule of thumb (all standard disclaimers about rules of thumb are in effect): mark your example variables private and provide public getters and setters for admission control. When you lot have more pattern and coding savvy in Java, you will probably do things a trivial differently, but for at present, this approach will continue you safe.

Note

Mark case variables private.

Marking getters and setters public.

"Sadly, Bill forgot to encapsulate his Cat grade and ended up with a flat true cat."

(overheard at the water cooler).

Encapsulating the GoodDog grade

image with no caption

Note

Even though the methods don't actually add new functionality, the cool affair is that y'all can change your listen after. you can come dorsum and brand a method safer, faster, improve.

Note

Any place where a particular value tin can be used, a method call that returns that type can be used.

instead of:

int x = 3 + 24;

y'all tin can say:

int x = iii + one.getSize();

How exercise objects in an array behave?

Just like whatsoever other object. The only difference is how yous get to them. In other words, how you get the remote command. Let's try calling methods on Dog objects in an assortment.

  1. Declare and create a Canis familiaris assortment, to hold seven Dog references.

                                          Canis familiaris[] pets;                                                        pets = new Canis familiaris[7];                                  

    image with no caption

  2. Create ii new Dog objects, and assign them to the first 2 array elements.

                                          pets[0] = new Dog();                                                        pets[one] = new Domestic dog();                                  
  3. Call methods on the two Dog objects.

                                          pets[0].setSize(30);                                                        int x = pets[0].getSize();                                                        pets[ane].setSize(eight);                                  

    image with no caption

Declaring and initializing instance variables

You already know that a variable declaration needs at least a proper name and a type:

                          int size;                                      String name;                      

And you know that you can initialize (assign a value) to the variable at the same time:

                          int size = 420;                                      String proper noun = "Donny";                      

But when you don't initialize an instance variable, what happens when you call a getter method? In other words, what is the value of an instance variable before you initialize it?

image with no caption

Note

Instance variables always go a default value. If you don't explicitly assign a value to an case variable, or yous don't call a setter method, the example variable all the same has a value!

integers

0

floating points

0.0

booleans

false

references

zip

image with no caption

Annotation

Y'all don't have to initialize instance variables, because they e'er accept a default value. Number primitives (including char) become 0, booleans get false, and object reference variables get nix.

(Remember, null but ways a remote command that isn't decision-making / programmed to anything. A reference, but no actual object.)

The deviation betwixt instance and local variables

  1. Instance variables are declared inside a course simply not within a method.

    grade Horse {    private double                                      height                                    = 15.2;    private Cord                                      breed;                                    // more than code... }
  2. Local variables are declared inside a method.

    class AddThing {    int a;    int b = 12;     public int add() {       int                                      total                                    = a + b;       return total;    } }
  3. Local variables MUST be initialized earlier apply!

    image with no caption

image with no caption

Local variables do Non get a default value! The compiler complains if yous effort to employ a local variable before the variable is initialized.

Comparing variables (primitives or references)

Sometimes you want to know if two primitives are the same. That'due south piece of cake enough, just apply the == operator. Sometimes yous want to know if 2 reference variables refer to a single object on the heap. Piece of cake equally well, just employ the == operator. But sometimes yous want to know if two objects are equal. And for that, you need the .equals() method. The idea of equality for objects depends on the type of object. For example, if two unlike String objects accept the same characters (say, "expeditious"), they are meaningfully equivalent, regardless of whether they are two distinct objects on the heap. But what about a Domestic dog? Do you want to care for two Dogs as being equal if they happen to take the aforementioned size and weight? Probably not. Then whether two different objects should be treated equally equal depends on what makes sense for that particular object type. We'll explore the notion of object equality over again in later on chapters (and Appendix B), just for now, nosotros need to sympathize that the == operator is used but to compare the bits in two variables. What those bits correspond doesn't affair. The $.25 are either the same, or they're not.

Note

Use == to compare ii primitives, or to run into if two references refer to the same object.

Use the equals() method to encounter if two dissimilar objects are equal.

(Such as two unlike Cord objects that both represent the characters in "Fred")

To compare two primitives, use the == operator

The == operator can be used to compare ii variables of whatever kind, and it just compares the $.25.

if (a == b) {...} looks at the $.25 in a and b and returns true if the bit pattern is the aforementioned (although it doesn't care about the size of the variable, so all the actress zeroes on the left end don't matter).

                          int a = 3;                                      byte b = 3;                                      if (a == b) { // true }                      

image with no caption

To see if two references are the same (which means they refer to the same object on the heap) apply the == operator

Remember, the == operator cares only about the pattern of bits in the variable. The rules are the aforementioned whether the variable is a reference or primitive. So the == operator returns true if two reference variables refer to the same object! In that instance, we don't know what the bit pattern is (because information technology's dependent on the JVM, and hidden from us) but we practise know that whatever it looks like, it will be the same for 2 references to a single object .

                          Foo a = new Foo();                                      Foo b = new Foo();                                      Foo c = a;                                      if (a == b) { // false }                                      if (a == c) { // truthful }                                      if (b == c) { // false }                      

image with no caption

image with no caption

parkeryoulthalater1997.blogspot.com

Source: https://www.oreilly.com/library/view/head-first-java/0596009208/ch04.html

0 Response to "When Check if Method True the Method Is Called Again"

ارسال یک نظر

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel