Monday, January 11, 2010

Programming: Java: Tutorials: Constructors, Sub-Routines, and Functions

 Certainly, I'd be glad to clarify for you.

When you have a "Sub-Routine" (pocket of code which just runs [fire and forget]) you aren't receiving anything back. You are just saying "go off and do this so I don't have to write out that code again".

A Function is like a Sub-Routine in the sense that it is a section of code that you can keep calling over and over again, accept that it also returns a value.

This can be seen in the code like so.

A sub-routine would be... (For a theoretical class called dog)

public void Bark() {
  System.out.println("Woof! Woof!!!");
}

Notice how seeing as we don't want to retrieve a value from the Bark() method we write Void in its header.

Now, lets say we wanted a Function to tell us how old the dog was... (Note "DogAge" is an integer variable)

public int getAge() {
  return DogAge;
}

Notice how because we want to retrieve an integer we place int instead of Void in the header. This makes the Function return an integer, which we give to it using the "return" command.

The difference is that if we wanted to make the dog bark we would literally type...

myDog.Bark();

and be done with it. But with a function we have to store the value it returns. Seeing as our Function in this case returns an integer, we store it like so...

int Age =  myDog.getAge();

Now we have created a new integer variable called age and given it a value from our Dog class.

But don't be fooled, a Function doesn't just have to return a pre-existing variable. Before we write...

return VAR;

at the end of the function, we can put any calculations we want.

This has been a very drawn out explanation. But don't worry it will become clear in time.

All you need to know about constructors and why I commented on them not "even" having Void in their header was that they are unique, and therefore easy to spot and manipulate.

//Beginning of the Dog Class
public class Dog() {

  //The variables to store information about the dog
  int DogAge;
  String Name;


  //Default Constructor
  public Dog() {
    DogAge = 5;
    Name = "Saxon";
  }


  //2nd Con. for if we want to specify an Age
  public Dog(int Age) {
     DogAge = Age;
     Name = "Saxon";
   }


  //3rd Con. for if we want to specify a Name
  public Dog(String name) {
     DogAge = 5;
     Name = name;
   }

  //4th Con. for if we want to specify a Name and Age
  public Dog(int Age, String name) {
     DogAge = Age;
     Name = name;
   }


  //A Sub-Routine to make the dog Bark
  public void Bark() {
    System.out.println("Woof! Woof!!!");
  }


  //A Function to retrieve the dogs Age
  public int getAge() {
    return DogAge;
  }


}

This sample class shows the fundamental differences between Constructors, Sub-Routines, and Functions.

I hope this helps.

No comments: