Object Programming  «Prev  Next»
Lesson 6Adding behavior with methods
ObjectiveGive objects behavior using methods.

Adding Behavior with Methods

In object-oriented programming, particularly in languages like Java, methods are fundamental for adding behavior to objects. Here's how methods work to achieve this:
Definition of Methods A method in Java is essentially a block of code that performs a specific task. Methods are defined within a class and can be invoked on objects of that class. Here's the basic structure of a method in Java:
[access_modifier] [return_type] methodName([parameters]) {
    // Method body
}
Access Modifier: Determines the visibility of the method (public, private, protected, or default). Return Type: Specifies what type of value the method will return, or void if it doesn't return anything. Method Name: A unique identifier for the method within the class. Parameters: Variables passed into the method which are used within the method body. How Methods Add Behavior: Encapsulation: Methods allow you to encapsulate behavior within a class. For instance, if you have a BankAccount class, you might have methods like deposit() or withdraw() which handle the logic for managing account balances.
public class BankAccount {
    private double balance;

    public void deposit(double amount) {
        if (amount > 0) {
            this.balance += amount;
        }
    }

    public void withdraw(double amount) {
        if (amount > 0 && this.balance >= amount) {
            this.balance -= amount;
        }
    }
}


Polymorphism: Methods can be overridden in subclasses, allowing different behavior based on the type of the object. This is key for polymorphism where a method call can lead to different behaviors depending on the actual object type.
class Animal {
    public void makeSound() {
        System.out.println("Some sound");
    }
}

class Dog extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Woof");
    }
}
Abstraction: Abstract methods in abstract classes or interfaces declare a behavior without providing an implementation, forcing subclasses to implement that behavior. This abstracts away the implementation details from the user of the class.
abstract class Shape {
    abstract double area();
}

class Circle extends Shape {
    private double radius;

    @Override
    double area() {
        return Math.PI * radius * radius;
    }
}
  • Reusability: Methods can be reused across different parts of the program. If you need to perform the same action multiple times, you write it once as a method and call it whenever needed.
  • Modularity: Methods promote modularity by breaking down complex operations into smaller, manageable pieces. This makes code easier to read, write, and maintain.
  • Interaction: Methods can interact with other methods or external systems, facilitating complex behavior through method calls, either within the same class or across different parts of the application.

By defining methods, you're essentially dictating how objects of a class will behave when certain actions are invoked on them. This approach not only organizes code into logical sections but also adheres to the principles of OOP like encapsulation, inheritance, polymorphism, and abstraction.


As you now know, objects possess two fundamental characteristics:
  1. state and
  2. behavior.

The state of an object is dictated by its member variables, while the behavior of the object is determined by its methods[1].
returnType methodName(parameter1) {
  // Code goes here MethodBody
}
int square(int n){
  return n*n;
}

It is often necessary for methods to return information regarding the task they have performed. The ReturnType specifies the type of data that a method returns. The MethodName is the name of the method. A method is also capable of receiving parameters that somehow determine how it functions. Method parameters are identified in the Parameters of the method definition. The actual code for the method is located in the MethodBody. Following is an example of a method:
boolean isHungry() {
  return hungry; 
}

Void Data Type

I want to clarify the usage of the void data type. The void data type is interesting in that it does not actually represent any data at all. It is a valid data type, but it represents the absence of data. In other words, in the eat() method a return type of void indicates that eat() does not return any data.
public void eat(){
  System.out.println("Within the eat method");
}

The purpose of a method is to complete a specific task within a program. The method can return a value once the task has been completed.
In some cases, a method must produce a result. If it does not, then it is considered void.
The type of value that a method can return is written to the immediate left side of the method name.
If the method does not return a data type, then type void to the immediate left of the method name.
The task that a method carries out is included between an opening curly bracket "{" and a closing curly bracket "}".
Here is an example:
public class House {
   long propertyNumber;
   String propertyType;
   byte Stories;
   public int Bedrooms;
   double MarketValue;
   void displayHouse() {
     System.out.println("Within the displayHouse method");
   }
}

This method makes a good addition to the Lion class.
The name of the method is isHungry(), and it returns data of type boolean. The isHungry() method accepts no parameters, as evident by the empty parentheses following the method name. The code in the isHungry() method simply returns the value of the hungry member variable.

Simple Class - Exercise

Click the Exercise link below to define a simple class.
Simple Class - Exercise

[1] : A method is a discrete section of code that can be called to perform a specific task. Following is the syntax used to define methods in Java: