Method signatures

Method signatures define/describe:

  • the name/identifier of the method
  • the parameters of the method (identifier and data type)
  • the return type of the method eg void or int etc

Objectives

Students will be able to:

  • understand the basic concept of method overriding
  • understand how to use the super keyword to call superclass methods when method overriding is used

Object Oriented Programming

Recursion

5 bunnies have waggly ears.

Each bunny says I'm hungry!

for(int i = 0; i<5; i++){

System.out.println("I'm hungry!");

}

A for loop is a great way to iterate/repeat a process.

Of course, we could also use a while loop:

int i = 0;

while(i<5){

System.out.println("I'm hungry!");

i++;

}

Or a do-while loop!

int i = 0;

do{

System.out.println("I'm hungry!");

i++;

}(while i<5);

Another interesting way to iterate is by using recursion.

Recursion

Open your IDE and follow along!

Recursion is when a function calls itself!

For example:

public static void main(String[] args){

hungry();

}

 

public static void hungry(){

System.out.println("I'm hungry!");

hungry(); //the recursive call

}

Code this and run it. What happens?! Stack Overflow?? You bet! The function kept calling itself and had no way to know when to stop. Basically, a pile of memory known as a stack is used to process recursive calls and it ran out of memory!

Base Case

We need to design the base case. This is the case where we tell the function to stop calling itself.

For example:

public static void main(String[] args){

hungry(5);

}

 

public static void hungry(int num){

if(num==0){ //base case

System.out.println("Finished! "+num);

}else{

System.out.println("I'm hungry! "+num);

hungry(num-1); //the recursive call

}

}

Code this and run it. Can you see how it works? The parameter value is always changing and eventually it reaches a value which tells the function to stop calling itself! The base case has been reached.

Returning values

What if we want a recursive function to return a value?

For example, we want a function, bunnyEars, to return how many ears a certain number of bunnies have.

The signature of this function could be:

public static int bunnyEars(int numBunnies)

We would expect that if numBunnies was 5, it would return 10 because bunnies have 2 ears.

How can we do this recursively? Watch this video to find out:

Go to and choose a (few) recursion challenge(s). The more examples you see and solve, the more you will understand how recursion works!

Exercises

Click the exercises button and see if you can complete the challenges.

Glossary

object

property

method

create an object/instance of a class

instantiate an object

encapsulate

access

mutate

abstraction

Tags

methodCoding Bat recursion base case recursive call stack overflow returnunwind