When a method uses a class name as its return type?

State affects behavior, behavior affects state. We know that objects have state and behavior, represented by instance variables and methods. But until now, we haven’t looked at how state and behavior are related. We already know that each instance of a class (each object of a particular type) can have its own unique values for its instance variables. Dog A can have a name “Fido” and a weight of 70 pounds. Dog B is “Killer” and weighs 9 pounds. And if the Dog class has a method makeNoise(), well, don’t you think a 70-pound dog barks a bit deeper than the little 9-pounder? (Assuming that annoying yippy sound can be considered a bark.) Fortunately, that’s 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 14 pounds, make yippy sound, else...” or “increase weight by 5”. Let’s go change some state.

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 can have different instance variable values. But what about the methods?

When a method uses a class name as its return type?

Can every object of that type have different method behavior?

Well... sort of.*

Every instance of a particular class has the same methods, but the methods can behave differently based on the value of the instance variables.

The Song class has two instance variables, title and artist. The play() method plays a song, but the instance you call play() on will play the song represented by the value of the title instance variable for that instance. So, if you call the play() method on one instance you’ll hear the song “Politik”, while another instance plays “Darkstar”. The method code, however, is the same.

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

When a method uses a class name as its return type?

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

A small Dog’s bark is different from a big Dog’s bark.

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

When a method uses a class name as its return type?

When a method uses a class name as its return type?

When a method uses a class name as its return type?

Just as you expect from any programming language, you can pass values into your methods. You might, for example, want to tell a Dog object how many times to bark by calling:

d.bark(3);

Depending on your programming background and personal preferences, you might use the term arguments or perhaps 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, we have bigger fish to fry in this book. So you can call them whatever you like (arguments, donuts, hairballs, etc.) but 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 like 2, “Foo”, or a reference to a Dog) lands face-down into a... wait for it... 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. And that something must be a value of the appropriate type.

When a method uses a class name as its return type?

Methods can return values. Every method is declared with a return type, but until now we’ve made all of our methods with a

Song t2 = new Song();
t2.setArtist("Travis");
t2.setTitle("Sing");
Song s3 = new Song();
s3.setArtist("Sex Pistols");
s3.setTitle("My Way");
6 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 back to the caller, such as:

int giveSecret() {
  return 42;
}

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

When a method uses a class name as its return type?

The compiler won’t let you return the wrong type of thing.

Whatever you say you’ll give back, you better give back!

When a method uses a class name as its return type?

Note

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

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, if a method has parameters, you must pass arguments of the right type and order.

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

When a method uses a class name as its return type?

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

When a method uses a class name as its return type?

When a method uses a class name as its return type?

  1. Declare an int variable and assign it the value ‘7’. The bit pattern for 7 goes into the variable named x.

    When a method uses a class name as its return type?

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

    When a method uses a class name as its return type?

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

    When a method uses a class name as its return type?

  4. 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.

    When a method uses a class name as its return type?

Note

When a method uses a class name as its return type?

Reminder: Java cares about type!

You can’t return a Giraffe when the return type is declared as a Rabbit. Same thing with parameters. You can’t pass a Giraffe into a method that takes a Rabbit.

Now that we’ve seen how parameters and return types work, it’s time to put them to good use: Getters and Setters. If you’re into being all formal about it, you might prefer to call them Accessors and Mutators. But that’s a waste of perfectly good syllables. Besides, Getters and Setters fits the Java naming convention, so that’s what we’ll call them.

Getters and Setters let 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 chance to take an argument value and use it to set the value of an instance variable.

When a method uses a class name as its return type?

class ElectricGuitar {

   String brand;
   int numOfPickups;
   boolean rockStarUsesIt;

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

When a method uses a class name as its return type?

Do it or risk humiliation and ridicule

Until this most important moment, we’ve been committing one of the worst OO faux pas (and we’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 data!

Here we are, just humming along without a care in the world leaving our data out there for anyone to see and even touch.

When a method uses a class name as its return type?

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

Exposed means reachable with the dot operator, as in:

theCat.height = 27;

Think about this idea of using our remote control to make a direct change to the Cat object’s size instance variable. In the hands of the wrong person, a reference variable (remote control) is quite a dangerous weapon. Because what’s to prevent:

When a method uses a class name as its return type?

This would be a Bad Thing. We need to build setter methods for all the instance variables, and find a way to force other code to call the setters rather than access the data directly.

Note

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

When a method uses a class name as its return type?

Yes it is that simple to go from an implementation that’s just begging for bad data to one that protects your data and protects your right to modify your implementation later.

OK, so how exactly do you hide the data? With the

Song t2 = new Song();
t2.setArtist("Travis");
t2.setTitle("Sing");
Song s3 = new Song();
s3.setArtist("Sex Pistols");
s3.setTitle("My Way");
7 and
Song t2 = new Song();
t2.setArtist("Travis");
t2.setTitle("Sing");
Song s3 = new Song();
s3.setArtist("Sex Pistols");
s3.setTitle("My Way");
8 access modifiers. You’re familiar with
Song t2 = new Song();
t2.setArtist("Travis");
t2.setTitle("Sing");
Song s3 = new Song();
s3.setArtist("Sex Pistols");
s3.setTitle("My Way");
7–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 have more design and coding savvy in Java, you will probably do things a little differently, but 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 up with a flat cat.”

(overheard at the water cooler).

When a method uses a class name as its return type?

Note

Even though the methods don’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.

Note

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

instead of:

int x = 3 + 24;

you can say:

int x = 3 + one.getSize();

Just like any other object. The only difference is how you get to them. In other words, how you get the remote control. Let’s try calling methods on Dog objects in an array.

  1. Declare and create a Dog array, to hold 7 Dog references.

    Dog[] pets;
    pets = new Dog[7];

    When a method uses a class name as its return type?

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

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

    pets[0].setSize(30);
    int x = pets[0].getSize();
    pets[1].setSize(8);

    When a method uses a class name as its return type?

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

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

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

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

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?

When a method uses a class name as its return type?

Note

Instance variables always get a default value. If you don’t explicitly assign a value to an instance variable, or you don’t call a setter method, the instance variable still has a value!

integers

0

floating points

0.0

booleans

false

references

null

When a method uses a class name as its return type?

Note

You don’t have to initialize instance variables, because they always have a default value. Number primitives (including char) get 0, booleans get false, and object reference variables get null.

(Remember, null just means a remote control that isn’t controlling / programmed to anything. A reference, but no actual object.)

  1. Instance variables are declared inside a class but not within a method.

    Song t2 = new Song();
    t2.setArtist("Travis");
    t2.setTitle("Sing");
    Song s3 = new Song();
    s3.setArtist("Sex Pistols");
    s3.setTitle("My Way");
    2
  2. Local variables are declared within a method.

    Song t2 = new Song();
    t2.setArtist("Travis");
    t2.setTitle("Sing");
    Song s3 = new Song();
    s3.setArtist("Sex Pistols");
    s3.setTitle("My Way");
    3
  3. Local variables MUST be initialized before use!

    When a method uses a class name as its return type?

When a method uses a class name as its return type?

Local variables do NOT get a default value! The compiler complains if you try to use a local variable before the variable is initialized.

Sometimes you want to know if two primitives are the same. That’s easy enough, just use the == operator. Sometimes you want to know if two reference variables refer to a single object on the heap. Easy as well, just use the == operator. But sometimes you 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 different String objects have the same characters (say, “expeditious”), they are meaningfully equivalent, regardless of whether they are two distinct objects on the heap. But what about a Dog? Do you want to treat two Dogs as being equal if they happen to have the same size and weight? Probably not. So whether two different objects should be treated as equal depends on what makes sense for that particular object type. We’ll explore the notion of object equality again in later 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 represent doesn’t matter. The bits are either the same, or they’re not.

Note

Use == to compare two primitives, or to see if two references refer to the same object.

Use the equals() method to see if two different objects are equal.

(Such as two different String objects that both represent the characters in “Fred”)

To compare two primitives, use the == operator

The == operator can be used to compare two variables of any kind, and it simply compares the bits.

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

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

When a method uses a class name as its return type?

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

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

Which method returns the name of the method?

Method Class | getName() Method in Java Method class is helpful to get the name of methods, as a String. To get name of all methods of a class, get all the methods of that class object. Then call getName() on those method objects. Return Value: It returns the name of the method, as String.

What is the return type of a method that returns any value?

A return type void is used when there is no return value. 2. Methods with return type and value: If a method is having int, double, float, etc other than void, we must return a value compatible with the declared return type by using the return statement.

Which method of the class is used to get the name of the class as a string?

getName. Returns the name of the entity (class, interface, array class, primitive type, or void) represented by this Class object, as a String .

What is called a method when it has same name as class name?

Explanation: A constructor is a method that initializes an object immediately upon creation. It has the same name as that of class in which it resides.