Java Lesson 11: Method Making

Advertisements

Welcome back loyal readers,

I’m back after a 34-day hiatus and ready to post more amazing content. This lesson will be on method making in Java, in other words, I will teach you how to create you own methods in Java.

Now, I know I covered method creation in the previous lesson on encapsulation. However, the methods I discussed were simply getter and setter methods; in this lesson, I will discuss how to create any type of method.

Here’s the basic syntax of a method:

    • public/private/protected [return type] method Name (parameter 1, parameter 2 …)

Now, what does this mean? Let me explain:

  • You would usually put public, private, or protected as the first part of the method. These three words serve as access modifiers, which denote which parts of the program can access the method. Here’s a better explanation on each:
    • public-any class in the program can access the method
    • private-only the class where the method is located can access the method
    • protected-the class where the method is located can access the method, but so can any classes in the same package as well as any subclasses of that class can also access that method (don’t worry I’ll demonstrate this later in this post)
  • A return type indicates what type of variable you want to return. The possible return types are the same as the the possible variable types (String, int etc.). However, keep these three things in mind regarding return types:
    • You can only return one item per method.
    • If you don’t want your method to return anything, simply use the word void as the return type.
    • Remember to write a line of code with return [variable name]
  • The method name is honestly pretty self-explanatory.
  • Inside the parentheses, you would put any parameters (variables inside the method) you wish to use-or you could use no parameters if you want. If you want to use multiple parameters, separate each individual parameter with a comma.

Now, let’s demonstrate some method making:

First, here’s our method class-this is the term I will use to describe any class where individual methods are made (not including the main method):

public class ProgramDemo
{
public int add (int a, int b)
{
return a+b;
}

public int subtract (int c, int d)
{
return d-c;
}

public int multiply (int e, int f)
{
return e*f;
}

public double divide (double g, double h)
{
return g/h;
}

public double square (int i)
{
return Math.pow(2, i);
}

public double log10 (double j)
{
return Math.log10(j);
}
}

And here’s our main class-this is the class which has the main method from which we will run this program:

public class Arithmetic
{
public static void main (String [] args)
{
ProgramDemo math = new ProgramDemo ();
System.out.println(math.add(45, 19));
System.out.println(math.subtract(18, 22));
System.out.println(math.multiply(36, 11));
System.out.println(math.divide(13.4, 2.3));
System.out.println(math.square(15));
System.out.println(math.log10(23));
}
}

And here’s the output:

64
4
396
5.82608695652174
32768.0
1.3617278360175928
BUILD SUCCESSFUL (total time: 0 seconds)

The class ProgramDemo is the method class since it has the methods that we will use for the program. The Arithmetic class is the main class since it has the main method, and it is the class from where we will run the program.

Notice how none of the ProgramDemo methods are void; all of the methods in that class have a return type, whether int or double.

In the main class-Arithmetic-I was able to access all of the methods of the ProgramDemo class simply by creating an object of the ProgramDemo class-math. There was no need to use extends here, as the methods are public and thus accessible by the entire program.

After I created the math object, I called all six of its methods, filled in each of the parameters for each method, and used System.out.println to print out the results of each calculation.

  • If you forgot what a logarithm is, here’s a simple explanation:
    • Screen Shot 2019-10-03 at 8.43.37 PM
    • For instance, the base 10 logarithm of 1000 would be 3, as 10 to the power of 3 equals 1000.

But what if our methods were private? Let’s demonstrate by first showing the ProgramDemo class with all of the private methods:

public class ProgramDemo
{
private int add (int a, int b)
{
return a+b;
}

private int subtract (int c, int d)
{
return d-c;
}

private int multiply (int e, int f)
{
return e*f;
}

private double divide (double g, double h)
{
return g/h;
}

private double square (int i)
{
return Math.pow(2, i);
}

private double log10 (double j)
{
return Math.log10(j);
}
}

Now, let’s try to execute our methods with the Arithmetic class  (using the same numerical parameters from the previous example):

public class Arithmetic
{
public static void main (String [] args)
{
ProgramDemo math = new ProgramDemo ();
math.add(45, 19);
math.subtract(18, 22);
math.multiply(36, 11);
math.divide(13.4, 2.3);
math.square(15);
math.log10(23);
}
}

And here’s what happens when we try to run the code:

Exception in thread “main” java.lang.RuntimeException: Uncompilable source code – add(int,int) has private access in ProgramDemo
at Arithmetic.main(Arithmetic.java:6)
/Users/michaelorozco-fletcher/Library/Caches/NetBeans/8.2/executor-snippets/run.xml:53: Java returned: 1
BUILD FAILED (total time: 5 seconds)

Since all of the ProgramDemo methods are private, we can’t access them from the Arithmetic class  (not even with the extends keyword). Notice that the error is something called an exception, which I will discuss more in a future post.

  • I imagine there’s probably a way to access private methods from another class, but I haven’t figured it out yet. Once I do, I’ll discuss it in a future post.

Now let’s make all of the ProgramDemo methods protected:

public class ProgramDemo
{
protected int add (int a, int b)
{
return a+b;
}

protected int subtract (int c, int d)
{
return d-c;
}

protected int multiply (int e, int f)
{
return e*f;
}

protected double divide (double g, double h)
{
return g/h;
}

protected double square (int i)
{
return Math.pow(2, i);
}

protected double log10 (double j)
{
return Math.log10(j);
}
}

And let’s run the code in the Arithmetic class (without changing the parameters):

public class Arithmetic
{
public static void main (String [] args)
{
ProgramDemo math = new ProgramDemo ();
math.add(45, 19);
math.subtract(18, 22);
math.multiply(36, 11);
math.divide(13.4, 2.3);
math.square(15);
math.log10(23);
}
}

Here’s the output:

run:
BUILD SUCCESSFUL (total time: 4 seconds)

OK, so this is a weird case where the methods are still accessible but don’t return anything; this is made even weirder since the methods aren’t of type void , so you would think that we would see returned values.

Interestingly enough, I tried several ways to fix my code so that the output would show (and yet none of them worked). Some of my attempted solutions include:

  • Creating a new package-JavaLesson11-and moving the Arithmetic and ProgramDemo classes to that package (I originally had them in the default package)
    • It’s very easy to create a new package in NetBeans. Simply click on the New File button (located above the interface) and when you are asked what type of file you want, simply click on New Package.
  • Using the phrase extends ProgramDemo in the Arithmetic class-I did this both before and after moving each of these classes into the JavaLesson11 package
    • This also did not work. I thought this would certainly would work, since protected methods can be accessed by subclasses of a certain class (the word extends make a class a subclass of whatever that class extends).
    • Also, after I moved Arithmetic and ProgramDemo to the JavaLesson11 package, I thought using extends would certainly work, since protected methods can be accessed by any class in the same package.

Cases like these are why I try to avoid using protected methods in my Java code. I’ll likely stick to public and private methods from here on out.

Now, the last thing I want to demonstrate is how void methods work. Im going to change two methods in ProgramDemo to void and see if that impacts the output:

package JavaLesson11;

public class ProgramDemo
{
public void add (int a, int b)
{
System.out.println(a+b);
}

protected void subtract (int c, int d)
{
System.out.println(d-c);
}

protected int multiply (int e, int f)
{
return e*f;
}

protected double divide (double g, double h)
{
return g/h;
}

protected double square (int i)
{
return Math.pow(2, i);
}

protected double log10 (double j)
{
return Math.log10(j);
}

}

And here’s the ArithmeticClass along with the corresponding output:

package JavaLesson11;

public class Arithmetic extends ProgramDemo
{
public static void main (String [] args)
{
ProgramDemo math = new ProgramDemo ();
math.add(45, 19);
math.subtract(18, 22);
math.multiply(36, 11);
math.divide(13.4, 2.3);
math.square(15);
math.log10(23);
}
}

run:
64
4
BUILD SUCCESSFUL (total time: 0 seconds)

So I ran the code and only get two numbers-64 and 4-which correspond to the add and subtract methods, respectively. Surprisingly, none of the other results from my other methods were printed.

How could that be? First of all, I only made the add and subtract methods void. As a result, I changed the body of each method by replacing the return statement with a System.out.println line that does the same thing as the non-void add and subtract methods. My guess is that since add and subtract are the only two methods with a System.out.println statement in the body of the method, the results of these methods were the only ones that were displayed in the output.

Thanks for reading. It’s good to be back,

Michael

 

 

Leave a ReplyCancel reply