Python Lesson 14: Inheritance

Hello everybody,

Michael here, and today’s lesson will be on inheritance in Python. Inheritance in Python is the same concept as inheritance in Java-a child class inherits all of the methods and attributes from another class called the parent class. However, inheritance in Python is executed differently than inheritance in Java, and this post will describe how inheritance in Python works.

To demonstrate inheritance, let’s first create a parent class:

In the parent class Team, I have two functions-__init__ and printInfo. The __init__ function accesses the class’s two main parameters-teamName and Location. The printInfo function prints the String The {teamName} are located in {location}.

  • The f in the print line denote that the String I’m trying to print is an f-string literal, which is a neat way to format Strings and concatenate values.
  • When inputting the parameter names into the f-string literal, remember to use the keyword self (or whatever word you used in place of self) in front of the parameter name just as I did for self.teamName and self.location.

OK, so now let’s create an object of the Team class and execute the printInfo method:

Now let’s create a class called BasketballTeam, which will serve as a child class of the Team class:

Inheritance with Python classes is conceptually the same as inheritance with Java classes but inheritance with Python classes has much different syntax.

To create a child class in Python, use this general syntax: class ChildClass (ParentClass).

You’ll also notice that I used the pass keyword as the body of the BasketballTeam class. However, when it comes to child classes, pass doesn’t mean the class is empty. Instead, pass means that all methods and attributes from the parent class are inherited, but you don’t want to add any new methods or attributes to the child class that aren’t in the parent class.

Now let’s create an object of the BasketballTeam class and call the printInfo function:

Looks like the inheritance worked like a charm!

Now, what if we wanted to use the __init__ function for our child class instead of the pass keyword? Let’s see how we would execute that:

In this example, the child class’s __init__ function overrides the parent class’s __init__ function. However, the printInfo function is unaffected by this change.

To keep the parent class’s __init__ function, be sure to call the parent class’s __init__ function in the child class’s __init__ function:

  • As you can see, the printInfo function works the same regardless of whether I use the parent class’s __init__ function or the child class’s __init__ function.

Now, what if you wanted the child class to inherit all of the methods and attributes from the parent class? To do this, use the keyword super (with parentheses):

When using the super() keyword in a child class, keep these three things in mind:

  • Place the super() keyword in the body of the child class’s __init__ function.
  • After using the super() keyword, remember to call the __init__ function. Also remember to use all of the parameters of the child class’s __init__ function except for self (or whatever you decided to call the self parameter).
  • Super() inherits all of the methods and attributes from the parent class, so there’s no need to mention the parent class (Team in this case)

Now, what if we wanted to add an attribute that is exclusive to the child class? Let’s see how we can accomplish that:

To add an attribute that is exclusive to a child class, use this syntax: self.(name of attribute) = value of attribute. Also remember to place any new attributes in the body of the child class’s __init__ function (not the super().__init__ function call).

Now I need to make another change to my code? What could that be?:

I needed to include my new attribute yearFounded as a parameter in the child class’s __init__ function. Whenever you create a new attribute that is exclusive to the child class, you SHOULD include it as a parameter in the child class’s __init__ function. By doing so, any new attribute you created can be used as a parameter when creating an object of the child class.

  • You don’t absolutely need to include the new attribute(s) in the parameters of the child class’s __init__ function but if you don’t include them, you won’t be able to use the new attribute(s) when creating an object of the child class.

OK, but what if you also wanted to add a function exclusive to the child class? Let’s see how we can do that:

To add a function exclusive to the child class, simply create a new function in the body of the child class with self (or whatever you want to use in place of self) as the sole parameter. DO NOT place the new function in the body of the child class’s __init__ function!

As you can see here, the new function I added-teamDescription works perfectly with the child class BasketballTeam. However, watch what happens when I try to use the teamDescription function with an object of the parent class Team:

I can’t use the teamDescription function on the parent class Team because the teamDescription function is exclusive to the child class BasketballTeam; therefore, it can only be used by the child class.

Thanks for reading,

Michael

Python Lesson 11: Functions

Hello everybody,

Michael here, and today’s post will be a Python post on functions.

What is a Python function? Let me explain this concept using a Java method:

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

Methods in Java are blocks of code that run only when they are called. Data can be passed into a function in the form of parameters. Methods can return data as a result (unless the method is void, in which case there is no return type).

So what would this have to do with functions? Well, Java methods and Python functions behave the same way (with some differences); Python functions can do everything that Java methods can and behave similarly to Java methods. Python functions only run when they are called. You can pass data into Python functions in the form of parameters. Python functions can also return data as a result.

Now let’s create a simple function, which calculates someone’s BMI based on their height and weight:

python1

First thing to remember is that all functions in Python start with def. It doesn’t matter what type of value the function is returning or the value type of the parameters-all functions in Python start with def. To call the function, simply use the function name followed by parentheses.

Also, all Python functions start with a colon and always have indented bodies; Java methods, on the other hand, start and end with curly brackets and don’t always have indented bodies.

Another thing you probably noticed  is that the two parameters don’t have the value type mentioned; in other words, you just see weight and height-not int weight or int height. This is because, unlike in Java, mentioning value types isn’t necessary in Python functions.

The fact that you don’t need to mention a value type in the function parameters also allows for more flexibility with your function. For instance, I could pass either int or float values in the BMI function and the function would work fine; however, if you try to pass a non-numerical value into the parameters, you’d likely get an error.

In this example, I used 166 and 70 as parameters (which represent the weight and height (in inches), respectively). The result is a BMI of 23.8 (rounded to one decimal place).

Another thing to keep in mind with Python functions is that if there are a certain number of parameters passed into a function, then when you call that function, you must use the same number of parameters-no more, no less. For example, the BMI function takes two parameters-weight and height-so if you try more or less than two parameters into the function when you call it, you will get an error.

Well, that holds true for the most part. See, with Python functions, you must remember to use the correct number of parameters when you call the function. But there is a workaround to this rule that you can’t find in Java-its the *args functionality.

*args is shorthand for arbitrary arguments*, and you would use this functionality if you don’t know how many arguments your function will use. Here’s an example of *args in action:

*The terms arguments and parameters are used interchangeably in the context of Python functions; you’ll see me using these terms interchangeably as well.

python2

To use the *args functionality, simply place an asterisk right next to the variable that you want to use as a parameter. In this example, I want to use the *args functionality for the cities variable.

So for functions with the *args functionality, the parameter would be a tuple rather than a single value. However, for the function to know which value in the tuple to return, remember to specify the index by the variable name; in this case, I used cities[3] to tell the function to return the 4th value in the tuple (whatever that might be).

  • A good suggestion to keep in mind when using the *args functionality is that, when you want to select a particular element from the tuple, be sure that the index exists in the tuple. For instance, if I had selected cities[5] from the tuple in the example, I would’ve gotten an error since there was no index 5 in the tuple.

*args isn’t the only cool functionality when it comes to Python functions. There is another functionality called *kwargs (short for keyword arguments) which allows you to send arguments to the function as a list of keys and values (like you would have in a dictionary). Let’s demonstrate the *kwargs functionality:

python3

In this example, the parameters for the teams function are specified as pairs of keys (team1, team2, and team3) and values (Philadelphia 76ers, Miami Heat, and LA Lakers). The key team2 is specified in the print line of the function; this tells the function to return the value that corresponds to team2, which is Miami Heat.

But what happens if you don’t specify a certain number of key-value pairs for the parameters? You can use the **kwargs functionality (which is shorthand for arbitrary keyword arguments), which is like the *kwargs functionality except you don’t need to specify how many key-value pairs the function will use (also, the **kwargs functionality uses two asterisks right by the variable name in the parameter, but this seemed pretty obvious).

Let’s take a look at the **kwargs functionality in action:

python4

In this example, the function firstName receives a dictionary of arguments and can access the items according to the key called in the print line-in this case, the key name1 is being called, so the corresponding value that will be printed is Michael.

  • In order to indicate the value that you would like to return, call the corresponding key in the function. If you try to call the value, you’ll get an error.

OK, so I’ve discussed parameter values and arbitrary parameter values. But what happens when we have a default parameter value? Let’s take a look:

python5

In this example, I set the default parameter value of age to 24. I then called the function twice, first with empty parentheses, then with a parameter of 22. When I called the function with empty parentheses, 24 was returned as the value for age. However, when I used 22 as a parameter, the default value for age was over-ridden and 22 was instead returned as the value for age.

  • You likely noticed that I have 24 and 22 as String, not int. This is because String variables can only be concatenated with other String variables.

By now, you have a better idea as to how to pass individual values as parameters in Python functions. However, you can also pass any other type of value as a parameter in a Python function (whether it’s a list, tuple, dictionary, etc.). As a matter of fact, I already demonstrated passing a dictionary as a parameter when discussing the *args and **kwargs functionalities. Now let’s demonstrate passing a list as a parameter:

python6

In this example, I pass the list days as a parameter in the function listFunction. I also make sure to include a for loop to iterate through the list.

  • In this example, there is only supposed to be one parameter for this function, which means you’re only supposed to pass one list through the function. However, you can have an unlimited number of values in the list.

Next, here’s an example of how functions can return values with the return statement:

python7

In this example, the function division is returning the value of the parameter divided by 5. The way to call a function with a return statement is different than the way to call a function without a return statement; you need to place the function call-division()-inside a print statement.

Now the last thing I want to mention regarding Python functions is that, unlike Java methods, they can’t be empty. Well, there is a workaround….:

python8

To create a function with no content, simply use the keyword pass in the body of the function, and you’ll be able to create it without running into an error (and yes, I know the name emptyFunction is oxymoronic as functions can’t be empty).

Thanks for reading,

Michael

Java Program Demo 3: More Fun With Method Making, Exceptions, Recursion, and Encapsulation

Hello readers,

It’s Michael, and today’s post will be another Java program demo utilizing the concepts covered in the previous four posts (encapsulation, method making, exceptions, and recursion). I thought this would be a good post to show more examples using these four concepts (as well as build upon the other concepts I discussed in the previous 9 Java posts, because after all, the harder concepts in Java build upon the easier concepts).

First let’s do an encapsulation demo. Here’s our method class (the one that has our getter and setter methods):

package demo3;

public class Demo3
{
private double surfaceArea;
private double volume;

public double setSurfaceArea (double radius, double height)
{
surfaceArea = (2*3.14*Math.pow(radius,2)) + (2*3.14*radius*height);
return surfaceArea;
}

public double setVolume (double radius, double height)
{
volume = (3.14*Math.pow(radius, 2)*height);
return volume;
}

}

And here’s our main class (the class where we will run the program):

package demo3;
import java.util.Scanner;

public class DemoClass3
{
public static void main (String [] args)
{
Demo3 cylinder = new Demo3();

Scanner sc = new Scanner(System.in);

System.out.println(“Please give me a radius: “);
double r = sc.nextDouble();

System.out.println(“Please give me a height: “);
double h = sc.nextDouble();

System.out.println(“The cylinder’s surface area is ” + cylinder.setSurfaceArea(r, h));
System.out.println(“The cylinder’s volume is ” + cylinder.setVolume(r, h));
}
}

And here’s some sample output:

run:
Please give me a radius:
9.5
Please give me a height:
11.2
The cylinder’s surface area is 1234.962
The cylinder’s volume is 3173.912
BUILD SUCCESSFUL (total time: 30 seconds)

In the Demo3 class, I have two private double variables-surfaceArea and volume. My two setter methods-setSurfaceArea and setVolume-will set the values of the surfaceArea and volume variables. Oh, and in case you’re wondering where I got the formulas from, they are the formulas for the surface area and volume of a cylinder, respectively.

You will notice that I don’t have any getter methods here. Why? Since I am using formulas to set the values of surfaceArea and volume, using only the setter methods is fine; due to the nature of this program, there is no need to use getter and setter methods (and the code might have been more confusing if I had used both getters and setters).

In my main class, I have a Scanner object and two doubles-r and h-that will serve as the parameters for each setter method (r will be radius and h will be height). R and h will be set based on the user’s input.

  • One thing I wanted to mention that I didn’t mention earlier is that you don’t have to use the words get and set in your getter and setter methods, but it’s a good idea to do so.

Next, here’s a program demonstrating method making and exception handling. First, here’s the method class (the class that contains the method(s) needed for the program):

package demo3;

public class Demo3
{
private double windchill;

public void findWindchill (double airTemp, double windSpeed)
{
try
{
windchill = 35.74 + (0.6215*airTemp) – (35.75*Math.pow(windSpeed, 2)) + (0.4275*airTemp*Math.pow(windSpeed, 16));
System.out.println(“The windchill is: ” + windchill);
}

catch (Exception e)
{
System.out.println(“Sorry please enter a number”);
}
}
}

And here is the main class (the class from where we will run the program):

package demo3;

public class Demo3
{
private double windchill;

public void findWindchill (double airTemp, double windSpeed)
{
try
{
windchill = 35.74 + (0.6215*airTemp) – (35.75*Math.pow(windSpeed, 2)) + (0.4275*airTemp*Math.pow(windSpeed, 16));
System.out.println(“The windchill is: ” + windchill);
}

catch (Exception e)
{
System.out.println(“Sorry please enter a number”);
}
}
}

And here are two sample outputs (one where the exception runs and one where the program runs normally):

run:
Please enter the temperature:
12
Please enter wind speed:
55
The windchill is : 3.596834017946246E28
BUILD SUCCESSFUL (total time: 3 seconds)

run:
Please enter the temperature:
12
Please enter wind speed:
H
Exception in thread “main” java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextDouble(Scanner.java:2413)
at demo3.DemoClass3.main(DemoClass3.java:15)
/Users/michaelorozco-fletcher/Library/Caches/NetBeans/8.2/executor-snippets/run.xml:53: Java returned: 1
BUILD FAILED (total time: 5 seconds)

In this program, the method findWindchill will calculate the temperature with windchill using airTemp and windSpeed as parameters-both of which are double.

In the method findWindchill , I have included a try-catch statement. In the try portion, the block of code I will test will calculate and display the windchill. In the catch portion, the message Sorry please enter a number will be displayed should the method catch an error (which would involve either airTemp or windSpeed not being double).

Or so you would think that the Sorry please enter a number message will be displayed (I thought this would happen too). Here’s what you really see:

Exception in thread “main” java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextDouble(Scanner.java:2413)
at demo3.DemoClass3.main(DemoClass3.java:15)
/Users/michaelorozco-fletcher/Library/Caches/NetBeans/8.2/executor-snippets/run.xml:53: Java returned: 1
BUILD FAILED (total time: 5 seconds)

So why don’t you see the Sorry please enter a number message? It’s because that, when dealing with double input, Java will automatically throw an InputMismatchException if the input is non-numeric.

In other words, writing a try-catch statement in my findWindchill method wasn’t necessary. I’ll admit that I didn’t realize this at first, and only found out this would happen after browsing through a few StackOverflow forums. Hey, even I learn new things in programming every now and then.

  • StackOverflow is a great resource for any coding questions you might have, but keep in mind that you might have to look through a few forums until you get the answer that you need.

Lastly, here’s a recursion demo, starting with the method class. Notice anything familiar about this program?:

public class Demo3
{
private int month;
private int day;
private String year;

public String findMonth (int month)
{
String m = null;

switch(month)
{
case 1: m = “January”; break;
case 2: m = “February”; break;
case 3: m = “March”; break;
case 4: m = “April”; break;
case 5: m = “May”; break;
case 6: m = “June”; break;
case 7: m = “July”; break;
case 8: m = “August”; break;
case 9: m = “September”; break;
case 10: m = “October”; break;
case 11: m = “November”; break;
case 12: m = “December”; break;

default:
{
System.out.println(“ERROR”);
System.exit(0);

}

}

return m;
}

public String findDay1 (int day)
{
String d = null;

{
switch(day)
{
case 1: d = “1st”; break;
case 2: d = “2nd”; break;
case 3: d = “3rd”; break;
case 4: d = “4th”; break;
case 5: d = “5th”; break;
case 6: d = “6th”; break;
case 7: d = “7th”; break;
case 8: d = “8th”; break;
case 9: d = “9th”; break;
case 10: d = “10th”; break;
case 11: d = “11th”; break;
case 12: d = “12th”; break;
case 13: d = “13th”; break;
case 14: d = “14th”; break;
case 15: d = “15th”; break;
case 16: d = “16th”; break;
case 17: d = “17th”; break;
case 18: d = “18th”; break;
case 19: d = “19th”; break;
case 20: d = “20th”; break;
case 21: d = “21st”; break;
case 22: d = “22nd”; break;
case 23: d = “23rd”; break;
case 24: d = “24th”; break;
case 25: d = “25th”; break;
case 26: d = “26th”; break;
case 27: d = “27th”; break;
case 28: d = “28th”; break;
case 29: d = “29th”; break;
case 30: d = “30th”; break;

default:
{
System.out.println(“ERROR”);
System.exit(0);
}
}

return d;
}
}

public String findDay2 (int day)
{
String d2 = null;

switch(day)
{
case 1: d2 = “1st”; break;
case 2: d2 = “2nd”; break;
case 3: d2 = “3rd”; break;
case 4: d2 = “4th”; break;
case 5: d2 = “5th”; break;
case 6: d2 = “6th”; break;
case 7: d2 = “7th”; break;
case 8: d2 = “8th”; break;
case 9: d2 = “9th”; break;
case 10: d2 = “10th”; break;
case 11: d2 = “11th”; break;
case 12: d2 = “12th”; break;
case 13: d2 = “13th”; break;
case 14: d2 = “14th”; break;
case 15: d2 = “15th”; break;
case 16: d2 = “16th”; break;
case 17: d2 = “17th”; break;
case 18: d2 = “18th”; break;
case 19: d2 = “19th”; break;
case 20: d2 = “20th”; break;
case 21: d2 = “21st”; break;
case 22: d2 = “22nd”; break;
case 23: d2 = “23rd”; break;
case 24: d2 = “24th”; break;
case 25: d2 = “25th”; break;
case 26: d2 = “26th”; break;
case 27: d2 = “27th”; break;
case 28: d2 = “28th”; break;

default:
{
System.out.println(“ERROR”);
System.exit(0);
}
}
return d2;
}

public String findDay3 (int daÿ)
{
{
String d3 = null;

switch(day)
{
case 1: d3 = “1st”; break;
case 2: d3 = “2nd”; break;
case 3: d3 = “3rd”; break;
case 4: d3 = “4th”; break;
case 5: d3 = “5th”; break;
case 6: d3 = “6th”; break;
case 7: d3 = “7th”; break;
case 8: d3 = “8th”; break;
case 9: d3 = “9th”; break;
case 10: d3 = “10th”; break;
case 11: d3 = “11th”; break;
case 12: d3 = “12th”; break;
case 13: d3 = “13th”; break;
case 14: d3 = “14th”; break;
case 15: d3 = “15th”; break;
case 16: d3 = “16th”; break;
case 17: d3 = “17th”; break;
case 18: d3 = “18th”; break;
case 19: d3 = “19th”; break;
case 20: d3 = “20th”; break;
case 21: d3 = “21st”; break;
case 22: d3 = “22nd”; break;
case 23: d3 = “23rd”; break;
case 24: d3 = “24th”; break;
case 25: d3 = “25th”; break;
case 26: d3 = “26th”; break;
case 27: d3 = “27th”; break;
case 28: d3 = “28th”; break;
case 29: d3 = “29th”; break;
case 30: d3 = “30th”; break;
case 31: d3 = “31st”; break;

default:
{
System.out.println(“ERROR”);
System.exit(0);
}

}
return d3;
}
}

public String findYear (String year)
{
String y = null;

switch(year)
{
case “00”: y = “2000”; break;
case “01”: y = “2001”; break;
case “02”: y = “2002”; break;
case “03”: y = “2003”; break;
case “04”: y = “2004”; break;
case “05”: y = “2005”; break;
case “06”: y = “2006”; break;
case “07”: y = “2007”; break;
case “08”: y = “2008”; break;
case “09”: y = “2009”; break;
case “10”: y = “2010”; break;
case “11”: y = “2011”; break;
case “12”: y = “2012”; break;
case “13”: y = “2013”; break;
case “14”: y = “2014”; break;
case “15”: y = “2015”; break;
case “16”: y = “2016”; break;
case “17”: y = “2017”; break;
case “18”: y = “2018”; break;
case “19”: y = “2019”; break;

default:
{
System.out.println(“ERROR”);
System.exit(0);
}
}

return y;
}
}

And here’s the main class:

package demo3;
import java.util.Scanner;

public class DemoClass3
{
public static void main (String [] args)
{
Demo3 date = new Demo3 ();
Scanner sc = new Scanner (System.in);

System.out.println(“Please enter a number: “);
int month = sc.nextInt();

System.out.println(“Please enter a number: “);
int day = sc.nextInt();

System.out.println(“Please enter a two digit String: “);
String year = sc.next();

if (month == 4 || month == 6 || month == 9 || month == 11)
{
System.out.println(“The date is: ” + date.findMonth(month) + ” ” + date.findDay1(day) + ” , ” + date.findYear(year));
}

else if (month == 2)
{
System.out.println(“The date is: ” + date.findMonth(month) + ” ” + date.findDay2(day) + ” , ” + date.findYear(year));
}

else
{
System.out.println(“The date is: ” + date.findMonth(month) + ” ” + date.findDay3(day) + ” , ” + date.findYear(year));
}
}
}

And here are two sample outputs, one where the program runs as normal, and another where the default case is executed:

run:
Please enter a number:
11
Please enter a number:
27
Please enter a two digit String:
19
The date is: November 27th , 2019
BUILD SUCCESSFUL (total time: 13 seconds)

run:
Please enter a number:
11
Please enter a number:
31
Please enter a two digit String:
19
ERROR
BUILD SUCCESSFUL (total time: 6 seconds)

Alright, so the familiar thing about this program is that it is a more complicated version of the recursion example from Java Lesson 13: Recursion (the one where you enter a number and return a month). However, unlike that program, you are trying to put together a whole date using three variables-month, day, and  year.

But that’s not all. See, the month and day variables are int but the year is actually a String. Ok, so year is really a two-digit String that can range from 00 to 19 (representing 2000 to 2019). From that two-digit string, the full year is returned.

The method class has 5 methods: findMonth, findDay1, findDay2, findDay3 and findYear.  If you’ll notice from the code,  the findDay methods do the same basic thing; the only difference is that findDay1 has 30 cases, findDay2 has 28 cases, and findDay3 has 31.

As for why I made three different findDay methods, here’s a poem that explains my reasoning:

Thirty days hath September
April, June and November
All the rest have 31
Except for February which has 28

See, depending on the value for the month that the user enters, I needed three different findDay methods to handle every appropriate scenario, since not all months have the same amount of days.

And yes, I know February has a 29th every four years, but I didn’t feel like overcomplicating this program. If you tried to input a date such as February 29, 2016, you would get an error:

run:
Please enter a number:
2
Please enter a number:
29
Please enter a two digit String:
16
ERROR
BUILD SUCCESSFUL (total time: 21 seconds)

As for the two pieces of sample output shown earlier, the first piece shows the output when month=11, day=27, year="19" (that output is November 27, 2019 , the day this post was published). The second piece shows the output when month=11, day=31, year "19" (this returns an error message, since there is no such date as November 31, 2019).

Thanks for reading and Happy Thanksgiving,

Michael

Java Lesson 11: Method Making

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