Path Menu Get Unstuck Tools: My Home
Path Menu Get Unstuck Tools: My Home
Path Menu
Connected to Codecademy
Get Unstuck
Tools
Learn
LEARN JAVA: METHODS
Adding Parameters
We saw how a method’s scope prevents us from using variables declared in one method in
another method. What if we had some information in one method that we needed to pass into
another method?
Similar to how we added parameters to constructors, we can customize all other methods to
accept parameters. For example, in the following code, we create a startRadio() method that
accepts a Double parameter, stationNum, and a String parameter called stationName:
class Car {
String color;
Through method overloading, our Java programs can contain multiple methods with the same
name as long as each method’s parameter list is unique. For example, we can recreate our above
program to contain two startRadio() methods:
// Method 1
public void startRadio(double stationNum, String stationName) {
System.out.println("Turning on the radio to " + stationNum + ", "
+ station + "!");
System.out.println("Enjoy!");
}
// Method 2
public void startRadio(double stationNum) {
System.out.println("Turning on the radio to " + stationNum + "!");
}
Instructions
1.
Add a method to the Store class called greetCustomer(). It should be accessible by other classes,
and return no output. For now, have it take no parameters and leave the body of the method
empty.
Checkpoint 2 Passed
Hint
If we wanted to write a method called bark() that is accessible by other classes and produces no
output, we would use syntax like:
}
2.
Modify the greetCustomer() method so that it accepts a String parameter called customer.
Checkpoint 3 Passed
Hint
To add a parameter to a method signature, you put it in the parentheses:
}
3.
Inside of the greetCustomer() method, add a print statement to print:
4.
Inside the main() method, call the greetCustomer() method on the lemonadeStand object. Pass in
a String argument of your choice!
Checkpoint 5 Passed
Hint
If I were calling this method to greet myself, I would use the line:
lemonadeStand.greetCustomer("Laura");
store.java
// instance fields
String productType;
// constructor method
productType = product;
}
// advertise method
System.out.println(message);
// main method
lemonadeStand.greetCustomer("Laura");
}
My Home
Path Menu
Workspace restored.
Get Unstuck
Tools
Learn
LEARN JAVA: METHODS
Reassigning Instance Fields
Earlier, we thought about a Savings Account as a type of object we could represent in Java.
public SavingsAccount{
double balance;
public SavingsAccount(double startingBalance){
balance = startingBalance;
}
}
}
These methods would change the value of the variable balance. We can reassign balance to be a
new value by using our assignment operator, =, again.
Changing instance fields is how we change the state of an object and make our objects more
flexible and realistic.
Instructions
1.
We have added a price instance field to the Store class.
However, to combat inflation costs, we’ve found ourselves increasing the price of our product
over and over. We’ve added an empty increasePrice() method to the Store class. It takes
a double parameter priceToAdd.
2.
Inside of increasePrice(), set the instance field price to be newPrice!
Checkpoint 3 Passed
3.
In the main() method, increase the price at the lemonade stand by 1.5. Then, print
the lemonadeStand.price to see how it has changed!
Checkpoint 4 Passed
Store.java
// instance fields
String productType;
double price;
// constructor method
productType = product;
price = initialPrice;
price = newPrice;
// main method
lemonadeStand.increasePrice(1.5);
System.out.println(lemonadeStand.price);
}
}
My Home
Path Menu
Connected to Codecademy
Get Unstuck
Tools
Learn
LEARN JAVA: METHODS
Returns
Remember, variables can only exist in the scope that they were declared in. We can use a value
outside of the method it was created in if we return it from the method.
In past exercises, when creating new methods, we used the keyword void. Here, we are
replacing void with int, to signify that the return type is an int.
The void keyword (which means “completely empty”) indicates that no value is returned after
calling that method.
We learned how to return primitive values from a method, but what if we wanted our method to
return an object? Returning an object works a little differently than returning a primitive value.
When we return a primitive value, a copy of the value is returned; however, when we return an
object, we return a reference to the object instead of a copy of it.
Let’s create a second class, carLot, that takes in a Car as a parameter and contains a method
which returns a Car object.
class CarLot {
Car carInLot;
public CarLot(Car givenCar) {
carInLot = givenCar;
}
Car@2f333739
Car@2f333739
Instructions
1.
We want to have a method that returns the price plus tax.
Define a method called getPriceWithTax() that is intended to return the price plus the tax. It
should take in no parameters and return a double.
You can leave the body of the method empty for now. Note: the code will have an error until we
return the correct type from the method, which we will do in the next step.
Hint
To create a method called getNumBarks() that returns an int, we would use the syntax:
Then, return totalPrice.
Hint
You can also accomplish this by defining a variable called tax, and then multiplying
by tax instead:
// instance fields
String productType;
double price;
// constructor method
productType = product;
price = initialPrice;
price = newPrice;
return totalPrice;
// main method
System.out.println(lemonadePrice);
}
My Home
Path Menu
Connected to Codecademy
Get Unstuck
Tools
Learn
LEARN JAVA: METHODS
The toString() Method
When we print out Objects, we often see a String that is not very helpful in determining what the
Object represents. In the last lesson, we saw that when we printed our Store objects, we would
see output like:
Store@6bc7c054
where Store is the name of the object and 6bc7c054 is its position in memory.
This doesn’t tell us anything about what the Store sells, the price, or the other instance fields
we’ve defined. We can add a method to our classes that makes this printout more descriptive.
When we define a toString() method for a class, we can return a String that will print when we
print the object:
class Car {
String color;
Instructions
1.
In the main() method, print the Objects lemonadeStand and cookieShop. Are these printouts helpful
in understanding these Objects?
2.
Create a toString() method for the Store class. The method signature should say that it is public,
and that it returns a String. It shouldn’t take in any parameters. For now, have it return
the String "Store".
3.
"Store" isn’t very helpful! What kind of Store is it?
// instance fields
String productType;
double price;
// constructor method
productType = product;
price = initialPrice;
price = newPrice;
return totalPrice;
// main method
public static void main(String[] args) {
}
My Home
Path Menu
Workspace restored.
Get Unstuck
Tools
Learn
LEARN JAVA: METHODS
The toString() Method
When we print out Objects, we often see a String that is not very helpful in determining what the
Object represents. In the last lesson, we saw that when we printed our Store objects, we would
see output like:
Store@6bc7c054
where Store is the name of the object and 6bc7c054 is its position in memory.
This doesn’t tell us anything about what the Store sells, the price, or the other instance fields
we’ve defined. We can add a method to our classes that makes this printout more descriptive.
When we define a toString() method for a class, we can return a String that will print when we
print the object:
class Car {
String color;
Instructions
1.
In the main() method, print the Objects lemonadeStand and cookieShop. Are these printouts helpful
in understanding these Objects?
Checkpoint 2 Passed
2.
Create a toString() method for the Store class. The method signature should say that it is public,
and that it returns a String. It shouldn’t take in any parameters. For now, have it return
the String "Store".
Checkpoint 3 Passed
3.
"Store" isn’t very helpful! What kind of Store is it?
4.
Look at the printouts again. Are they more helpful now?
My Home
Path Menu
Workspace restored.
Get Unstuck
Tools
Learn
LEARN JAVA: METHODS
Review
Great work! Methods are a powerful way to abstract tasks away and make them repeatable. They
allow us to define behavior for classes, so that the Objects we create can do the things we expect
them to. Let’s review everything we have learned about methods so far.
Defining a method : Methods have a method signature that declares their return type,
name, and parameters
Calling a method : Methods are invoked with a . and ()
Parameters : Inputs to the method and their types are declared in parentheses in the
method signature
Changing Instance Fields : Methods can be used to change the value of an instance field
Scope : Variables only exist within the domain that they are created in
Return : The type of the variables that are output are declared in the method signature
As you move through more Java material, it will be helpful to frame the tasks you create in terms
of methods. This will help you think about what inputs you might need and what output you
expect.
Instructions
1.
Now that we’ve learned about behavior, we can apply behavior to our SavingsAccount class using
methods!
We’ve added the functionality for each method inside main() now, but you will be rebuilding
each above main(). Note that your methods can directly access the balance field.
Hint
A checkPrice() method for our Store class would have looked like:
Hint
An addInventory() method for our Store class would have looked something like:
5.
Congratulations! You’ve made a basic SavingsAccount.
If you want, you can add more functionality to this! What other instance fields might you want to
keep track of? What might a toString() look like for this class?
int balance;
balance = initialBalance;
System.out.println("Hello!");
return amountToWithdraw;
}
//Check balance:
savings.checkBalance();
//Withdrawing:
savings.withdraw(300);
//Check balance:
savings.checkBalance();
//Deposit:
savings.deposit(600);
//Check balance:
savings.checkBalance();
//Deposit:
savings.deposit(600);
//Check balance:
savings.checkBalance();
System.out.println(savings);
https://discuss.codecademy.com/t/build-a-droid-help/512527