LEARN JAVA: METHODS
The first line,
public void startEngine()
, is the method signature. It gives the program some information about the method:public
means that other classes can access this method. We will learn more about that later in the course.- The
void
keyword means that there is no specific output from the method. We will see methods that are notvoid
later in this lesson, but for now all of our methods will bevoid
. startEngine()
is the name of the method.- public void startEngine() { System.out.println("Starting the car!"); System.out.println("Vroom!"); }
We mark the domain of this task using curly braces:
{
, and }
. Everything inside the curly braces is part of the task. This domain is called the scope of a method.
public void advertise() {
String message = "Selling " + productType + "!";
System.out.println(message);
}
This lesson also involve using string methods, and in order to print messages out, we use the line given above, but change the productType into the product you want.
The whole code should be divided into four parts showed below. In the instance fields, it includes the basic format for the variables that we need, which will be plugged into the second part which is the constructor method. The constructor method allows us to include the the basic variables into it. Then we can plug in the variables in the third part, then put in the numbers into the last part.
Note: For part three, there could be more than one as there are different needs for different projects, just remember to label it into comment form above if need.
public class Store {
// instance fields
String productType;
double price;
// constructor method
public Store(String product, double initialPrice) {
productType = product;
price = initialPrice;
}
// increase price method = advertise method
public void increasePrice(double priceToAdd){
double newPrice = price + priceToAdd;
price = newPrice;
}
// main method
public static void main(String[] args) {
Store lemonadeStand = new Store("Lemonade", 3.75);
lemonadeStand.increasePrice(1.5);
System.out.println(lemonadeStand.price);
}
}
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;
public Car(String carColor) {
color = carColor;
}
public static void main(String[] args){
Car myCar = new Car("red");
System.out.println(myCar);
}
public String toString(){
return "This is a " + color + " car!";
}
}
What I learned in this lesson..
I learned how to use java language to code, and learned that there are four main part of the code, which allows me to tell the computer what to do.
What I'm doing tomorrow...
CONDITIONALS AND CONTROL FLOW Decisions
No comments:
Post a Comment