CS101: Methods

Welcome to part 4 of CS101: Methods. You’ve seen one of these already- that ugly line called main in the previous article. You’ve probably figured this out, but a method is just a way of grouping a whole bunch of code together and giving it a name. Then, next time you need to perform that same task, you can just use the method instead of repeating your code. Neato. A simple concept, but looking at real code always helps. Let’s keep building our Warrior example from last time.

Well look at that, our program cleaned up a lot! By putting code that would otherwise be duplicated into methods we can make our code significantly easier to both read and use. You may have noticed the  public void  in front of our method. The first word is a modifier, which sets where we can access this method from. Public and private are the ones you’ll see the most. Public means it can be accessed from anywhere. Private means it can only be accessed inside of that class. We can use these on variables declarations, too. Void is our return type. See, methods can be used to calculate a value or result; we call that the return value. Void simply means we aren’t returning anything. Any type can be used instead of void as long as you include a matching return statement.

Then we have those empty parenthesis at the end. Methods can take in arguments to change how they behave. An argument is a value or object that we pass in to a method. You can already see this in our main method, although we never use the value we pass in. Arguments are listed first by type and then by name, separated with a comma if there are more than one.

Last time, we ended with a mention of constructors. A constructor is a method that is called automatically when an object is instantiated. It looks like this:

Even neater! As you can see, constructors use the parenthesis after the class name to pass in arguments. You’ll also notice that since we no longer need to set our variables outside of the class, I’ve made them private. When designing your classes, pay very careful attention to what you leave accessible to the outside. They should be a bit of a black box- other parts of your program know how to use them, but don’t know or care how they work. When classes start relying on each other to function, you are on the dangerous road to spaghetti code.

That’s it for today! Next time, we’ll start getting into the real meat of classes and objects- inheritance and polymorphism.

Next Post: Inheritance and Polymorphism


  1. I really liked your post.Really thank you! Guiles

Leave a Reply

Your email address will not be published / Required fields are marked *