Methods and classes – Java Tutorial

Methods and classes – Java Tutorial

Methods are statements that do what you ask them to. An example of a method would be inserting an address. You’d call the method “anAddress();” from the main(), then create the method “public static void anAddress()” with the address inside this method. You can use the same method in many different programs as long as you provide the class it’s coming from. If you had a method named “anAddress();”, and it was in a class called “Different” instead of “First”, but you wanted to use it in First, you would have to type it as First.anAddress();. You can also create methods that require single or multiple arguments. For instance, say you wanted to create a class that holds two integer variables with values assigned. You would create two methods that compute the sum of and the difference between those values by calling the values from the main. Then, say you wanted to add a method that computes the product of the values, but instead of printing the values, you wanted to return the values to the main() for printing. You would end up with a program that looks something like this:
public class Numbers
{
public static void main(String[] args)
{
int value1 = 40, value2 = 30;
sum(value1, value2);
difference(value1, value2);
int prod;
prod = product(value1, value2);
System.out.println("The product is " + prod);
}

The Methods and classes


public static void sum(int num1, int num2)
{
int add;
add = num1 + num2;
System.out.println("The sum is " + add);
}
public static void difference(int dif1, int dif2)
{
int minus;
minus = dif1 - dif2;
System.out.println("The difference is " + minus);
}
public static int product(int mult1, int mult2)
{
int times;
times = mult1 * mult2;
return times;
}
}
If you compiled this program and ran it, you would get:

The sum is 70
The difference is 10
The product is 1200

This is called implementation hiding, where you don’t know how the program is executed, you just know it works. Notice the word return at the end of this program. This statement tells the program what value to return to the main(). For methods that return a value, you need to omit the void identifier and add the data type (i.e. int, double, String, etc.). Below is an example of a program that returns two values to the main().

public class Exponent
{
  public static void main(String[] args)
  {
    int num = 5;
    int totalSquared = square(num);
    System.out.println(totalSquared);
    int totalCubed = cube(num);
    System.out.println(totalCubed);
  }

  public static int square(int s)
  {
    int sqr = s * s;
    return sqr;
  }

  public static int cube(int c)
  {
    int cb = c * c * c;
    return cb;
  }
}

NOTE: For each method that is returning a value, you must have a separate declaration to print the values properly (i.e. int totalSquared = square(num); and int totalCubed = cube(num);).

Classes, on the other hand, are more like the make of a car, bodies of water, yogurt, etc. An Escort is a part of the Ford class. Pacific is a part of the Ocean class. Yogurt is a part of the dairy class, and so on. Classes are created when you type public class NameOfTheClass. The types of accesses that are allowed are private, public, friendly, protected, private protected, static, and final. Objects are instantiations of a class, which means they inherit their attributes from classes.

Here is a class that contains multiple methods to manipulate the given data:

public class Student
{
private int idNumber;
private int hoursEarned;
private double pointsEarned;
private double pointAverage;
Student()
{
idNumber = 42;
hoursEarned = 3;
pointsEarned = 3.5 * hoursEarned;
pointAverage = pointsEarned / hoursEarned;
}
public int getIdNumber()
{
return idNumber;
}
public int getHoursEarned()
{
return hoursEarned;
}
public double getPointsEarned()
{
return pointsEarned;
}
public double getPointAverage()
{
return pointAverage;
}
public void setIdNumber(int n)
{
idNumber = n;
}
public void setHoursEarned(int hrs)
{
hoursEarned = hrs;
}
public void setPointsEarned(double pts)
{
pointsEarned = pts;
}
public void setPointAverage(double ave)
{
pointAverage = ave;
}
}

Statements like public int getIdNumber() and public void setIdNumber(int n) configure the data so it can be used by the methods in the program. Notice the Student() method. This is what we call a constructor method. A constructor method establishes an object for the class to perform properly. In a sense, it allows the instantiations to instantiate the objects. In this next program, you’ll see how objects are instantiated:

public class ShowStudent
{
public static void main(String[] args)
{
Student oneStudent = new Student();
System.out.println("Student id number is " + oneStudent.getIdNumber());
System.out.println("Number of hours earned " + oneStudent.getHoursEarned());
System.out.println("Points earned " + oneStudent.getPointsEarned());
System.out.println("Grade point average is " + oneStudent.getPointAverage());
}
}

The line Student oneStudent = new Student(); instantiates the objects so that instantiations like oneStudent.getPointAverage() can receive and send their data.

These next programs put everything together that we’ve learned so far. The first program holds a patient number, two blood pressure figures(systolic and diastolic), and two cholesterol figures(LDL and HDL). One method named computeRatio() divides the two cholesterol figures. A second method named explainRatio() explains that a ratio of 3.5 or lower is good. The second program declares the necessary methods, provides values for each method, and displays the results. To do this, here’s what the programs look like:

Program One
public class Checkup
{
  private int patientNumber = 153;
  private int systolicBP;
  private int diastolicBP;
  private int infoLDL;
  private int infoHDL;
  private int bPressure;
  public static void computeRatio(int infoLDL, int infoHDL)
  {
    int comp = infoLDL / infoHDL;
    System.out.println("The ratio of good and bad cholesterol is " + comp + ".");
  }
  public static void explainRatio()
  {
    System.out.println("Cholesterol levels of 3.5 or lower are considered good.");
  }
  public int bloodPressure()
  {
    System.out.println("Blood pressure is " + systolicBP + "/" + diastolicBP);
    return bPressure;
  }
  public int getPatientNumber()
  {
    return patientNumber;
  }
  public int getSystolicBP()
  {
    return systolicBP;
  }
  public int getDiastolicBP()
  {
    return diastolicBP;
  }
  public int getInfoLDL()
  {
    return infoLDL;
  }
  public int getInfoHDL()
  {
    return infoHDL;
  }
  public void setPatientNumber(int n)
  {
    patientNumber = n;
  }
  public void setSystolicBP(int s)
  {
    systolicBP = s;
  }
  public void setDiastolicBP(int d)
  {
    diastolicBP = d;
  }
  public void setInfoLDL(int l)
  {
    infoLDL = l;
  }
  public void setInfoHDL(int h)
  {
    infoHDL = h;
  }
}

Program Two
public class TestCheckup
{
  public static void main(String[] args)
  {
    Checkup sysBP = new Checkup();
    Checkup diaBP = new Checkup();
    Checkup lChol = new Checkup();
    Checkup hChol = new Checkup();
    Checkup patNum = new Checkup();
    int sys;
    int dia;
    int l;
    int h;
    int pat;
    sysBP.setSystolicBP(110);
    diaBP.setDiastolicBP(78);
    lChol.setInfoLDL(100);
    hChol.setInfoHDL(40);
    sys = sysBP.getSystolicBP();
    dia = diaBP.getDiastolicBP();
    l = lChol.getInfoLDL();
    h = hChol.getInfoHDL();
    pat = patNum.getPatientNumber();
    System.out.println("Your patient number is " + pat);
    System.out.println("Your blood pressure is " + sys + "/" + dia);
    System.out.println("Your LDL cholesterol is " + l);
    System.out.println("Your HDL cholesterol is " + h);
    Checkup.computeRatio(l,h);
    Checkup.explainRatio();
  }
}

Question: You mean I have to create every line I want to use in my programs? Java’s been out for a while. And all this talk about “classes”. I thought I didn’t have to take any classes. Hasn’t someone already created objects that I can use?

Answer: Yes, and we will be getting to that in the next few lessons. Relax. You have to learn to crawl before you can walk. Next, you'll be learning about blocks, scopes, and overloading.