Last modified: January 07, 2024
Methods (also called functions) are the things an object can do. There are two kinds of methods:
Here are two examples of each:
This method returns (reports back) the person's height in inches
public double heightToInches() {
// 1 meter = 39.97 inches
double answer = myHeight * 39.97;
return answer;
}
This method returns (reports back) the person's name
public String getName() {
return myName;
}
This method prints info about the Person, but doesn't return any values
public void printInfo() {
String response;
response = "Hello, my name is " + myName;
response = response + " and I'm " + myAge + " years old!";
if (isStudent == true) {
response += " I am a student.";
}
else {
response += " I am not a student.";
}
System.out.println(response);
}
This method increases the Person's age by a given amount, but doesn't return any values
public void increaseAge(int amount) {
myAge = myAge + amount;
}
Adding these methods to our Person class, we have:
public class Person {
// Instance Variables - fields storing info about the state
// of an object (attributes/properties)
int myAge; // Age in years
double myHeight; // Height in meters
boolean isStudent; // True if enrolled at any school, false otherwise
String myName; // Person's name
// Constructors - Specialized methods that set an object up
// and initialize instance variables
public Person() {
myAge = 17;
myHeight = 1.53;
isStudent = false;
myName = "Frances";
}
public Person(int age, double height, boolean student, String name) {
myAge = age;
myHeight = height;
isStudent = student;
myName = name;
}
// Methods - The things an object can do
// Subroutines, or code, that define how an object behaves
public double heightToInches() {
// 1 meter = 39.97 inches
double answer = myHeight * 39.97;
return answer;
}
public String getName() {
return myName;
}
public void printInfo() {
String response;
response = "Hello, my name is " + myName;
response = response + " and I'm " + myAge + " years old!";
if (isStudent == true) {
response += " I am a student.";
}
else {
response += " I am not a student.";
}
System.out.println(response);
}
public void increaseAge(int amount) {
myAge = myAge + amount;
}
}
A few things to notice:
public data_type method_name () {
...
)
public void method_name () {
...
)
public void increaseAge (int amount) {
...
)