How to write methods in Java

Nilani Gunasekara
8 min readOct 19, 2021

--

We know Java is an object-oriented language where we map real-world objects into programming objects/instances. In that, we define a class with all the required behaviors and status of the real object. The behaviors are mapped to methods and statuses are mapped to instance variables.

Let's take the example of pets. We have different types of pets like cats, dogs, and rabbits, etc.
Consider a cat, that has a name and always likes to play.

How are we going to represent the above scenario in Java? First, we have to create a class to hold the status and behaviors.

  • Real-world (Status → name ) → Java (instance variable → name)
  • Real-world (behavior) → Java (method → play)

Behavior play is an action and the action has some steps like how it plays, the cat may touch its tail and play with it.

Before we map any behavior to a method we should think about the following;

  • Who can see/access and who can not see/access the behavior — modifier
  • Are we giving something to complete the behavior or not — parameters
  • What are the things we have to do in order to complete the behavior/action—method body
  • Are we expecting something in return at the end of the behavior or not— return type

Method Name— To cover the behavior/action we write methods. We give the behavior a name to identify it. Most of the time method name is a verb. The name starts with simple letters and if the name has more than one word the first letter of the second word will be in capital letter and the rest of the letters of the second word will be in simple letters. This is called camelcase.

Parameter list — Up to now, we have given a name to our behavior/action, then we have to think do we need to supply additional things that help the behavior/action to perform. To provide additional things there is a placeholder covered with open and close parenthesis (). If we have anything to supply we can add it inside the () if not we can keep it empty. When we do that we have to mention what type of things that we are going to add and which variable that would hold the value. We say these addition things as parameters. We can add more than one parameter to a method.

Method Body — Now we have to specify the steps that we need to complete, in our case how the cat plays. We say these steps as statements that are required to complete the method. We include these statements inside opened and closed curly brackets {}. This also defines the scope of the method.

Return type — The action completes when the statements inside the body are completed. As per the method play, once the cat stopped playing the action is completed. So the method is completed too. We did not expect anything to return as a result of the completed action. Therefore we can say, play method does not return anything so the play method is a void method. But there are scenarios where we expect something in return. As an example, if we have method sum, to get the aggregated value of two numbers, we are expecting the aggregated value. In that case, we have to return the expected value using the return keyword as the last line/statement in the method. Another thing to remember, when we expecting something in return we have to say that this method returns something of value x by mentioning the return type of the method. The return type should be placed before the method name.

Access modifiers — Now we know how to map the real-world scenario into Java method. The next thing is we have to consider who should be able to access this method? Do we need to restrict or give everyone access? We can decide it and give the required accessibility with access modifiers. The access modifier should be placed before the return type of the method.

In summary, a method in Java has,

  • modifier- accessibility of the method (public, protected, no modifier-default, private)
  • return type — void or a valid type
  • name - mandatory
  • parameters - zero or more
  • method body — steps to complete the behavior/action
Figure 1 - Method declaration

Method header = modifier+return type + method name + parameter list

Method signature = method name + parameter list

We can simplify the method structure further like this.

Figure 2 — A simplified version of methods structure

We need two methods to set the name of the cat and get the name of the cat. Consider that we need to set the cat’s name.

  • The method name should be a verb and written in camelcase — setName
  • Cat name is provided to set with —one parameter — the name is the type of String
  • Nothing is expected from play — no return — void
  • No access restriction needed — public

Consider that we need to get the cat’s name.

  • The method name should be a verb and written in camelcase — getName
  • Nothing is required to get the name — no parameters
  • Cat’s name is expected — cat's name should return — the name is the type of String
  • No access restriction needed — public

Consider the playing behavior of the cat.

  • The method name should be a verb and written in camelcase — play
  • Nothing is provided to play with — no parameters
  • Nothing is expected from play — no return — void
  • No access restriction needed — public
package com.medium.java.howto;public class Cat {    private String name;    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public void play() {        System.out.println("Cat is playing ....");    }}

Assume that the cat is playing with a ball, and the ball can be rolled over and reconsider the play behavior.

  • The method name should be a verb and written in camelcase — playWithBall
  • A ball is provided to play with — one parameter- a ball type of Ball
  • Nothing is expected from play — void
  • No access restriction needed — public
package com.medium.java.howto;public class Cat {    private String name;    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public void play() {        System.out.println("Cat is playing ....");    }    public void playWithBall(Ball ball) {        ball.roll();        System.out.println("Cat is playing with the ball....");    }}

The ball class would be like this with the rolling behavior.

package com.medium.java.howto;public class Ball{    public void roll() {        System.out.println("Ball is rolling");    }}

Assume that the cat is playing with a car, most of the time cat will roll the car here and there. So we can say the car is also having rolling behavior, and reconsider the play behavior.

  • The method name should be a verb and written in camelcase — playWithCar
  • A car is provided to play with — one parameter- a car type of Car
  • Nothing is expected from play —void
  • No access restriction needed — public
package com.medium.java.howto;public class Cat {    private String name;    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public void play() {        System.out.println("Cat is playing ....");    }    public void playWithBall(Ball ball) {        ball.roll();        System.out.println("Cat is playing with the ball....");    }    public void playWithCar(Car car) {        car.roll();        System.out.println("Cat is playing with the car....");    }}

The car class with rolling behavior

package com.medium.java.howto;public class Car{    public void roll() {        System.out.println("Car is rolling");    }}

Assume that the cat is playing with many more toys, then are we going to create a separate method for each toy? NO, we can not do that. We have to find a way to write a method where we can cover those scenarios. In this type of situation, polymorphism comes into the picture.

Polymorphism is the ability to be in many forms.

In this case, the ball, car all are in the same category “Toy”. So we can have a superclass named Toy and extend the Toy class from Ball, and Car classes. Because Ball is a toy, the car is a toy. With that, we can have a method like this.

  • The method name should be a verb and written in camelcase — playWithToy
  • A Toy is provided to play with — one parameter- a toy with Type Toy
  • Nothing is expected from play — void
  • No access restriction needed — public
package com.medium.java.howto;public class Cat {    private String name;    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public void play() {        System.out.println("Cat is playing ....");    }    public void playWithBall(Ball ball) {        ball.roll();        System.out.println("Cat is playing with the ball....");    }    public void playWithCar(Car car) {        car.roll();        System.out.println("Cat is playing with the car....");    }    public void playWithToy(Toy toy) {        toy.roll();        System.out.println("Cat is playing with the toy....");    }}

The playWithBall and playWithCar methods are no longer needed when we have the playWithToy method.

Since both car and ball are toys, we can have a class name Toy as the superclass of both ball and car. Since there is no object called a toy in the real world, we should not give chance to create Toy objects. A toy is just a category/classification. We can make Toy class an abstract class and give no chance to create an object of it.

We said that both have the rolling behavior. We can abstract the rolling behavior to an interface called Rollable.

package com.medium.java.howto;public interface Rollable {    void roll();}

We can assume that all the toys are rollable, then we can implement the Rollable interface in the Toy class.

package com.medium.java.howto;public abstract class Toy implements Rollable{}

We can extend the Toy class and overwrite the inherited rolling behavior in the Car class. By doing this we can define the steps for car rolling behavior in the form of statements.

package com.medium.java.howto;public class Car extends Toy{    public void roll() {        System.out.println("Car is rolling");    }}

We can extend the Toy class and overwrite the inherited rolling behavior in the Ball class. With this, we can include the steps of ball rolling behavior as the method body.

package com.medium.java.howto;public class Ball extends Toy{    public void roll() {        System.out.println("Ball is rolling");    }}

What do we need next? We have classes ready and have to use them and see how the cat plays with the toys. We need to consider the below steps.

  • To have a cat we need to create a cat object.
Cat cat = new Cat();
  • Set the name
cat.setName("Kitty");
  • To play with a ball we need to create a ball object.
Ball ball = new Ball();
  • To play with a car we need to create a car object.
Car car = new Car();

Once we have the object ready we can see the below behaviors

  • The cat plays with itself.
cat.play();
  • The cat plays with the ball.
cat.playWithToy(ball);
  • The cat plays with the car.
cat.playWithToy(car);
  • Get the cat’s name and print it to the console
System.out.println("Cat name is : "+cat.getName());

Consider the below class created to demo the cat play behavior.

package com.medium.java.howto;public class CatPlayDemo {    public static void main(String[] args) {        Cat cat = new Cat();        cat.setName("Kitty");        Ball ball = new Ball();        Car car = new Car();        cat.play();        cat.playWithToy(ball);        cat.playWithToy(car);        System.out.println("Cat name is : "+cat.getName());    }}

The output of the above code is as below.

Figure 3- Console output of the CatPlayDemo class

This is the end of the article and hopes you were enjoying while reading this article and able to add something to your knowledge.

Happy learning !!!

--

--

Nilani Gunasekara

By profession I'm a software engineer who enjoys teaching as a hobby and always willing to share knowledge with others.