Skip to the content.
Unit 5 5.1 5.2 5.4 5.41 5.5 5.6 5.7 5.8 5.9 HW

Writing Methods

What is a Method?!

A method is a block of code that belong to a class, very similar to a function.

Methods in Java can take inputs (parameters), perform actions, and return a value (or void if no value is returned).

Methods that are created by the programmer to perform tasks are called user-defined methods, while other methods can be built in (like System.out.println()).

Types of methods:

There are many different types of methods in Java, but here I’ll only highlight the two most common ones and the ones used by College board.

Instance Methods: Methods that belong to an instance of a class Instance methods require an object of the class to be used. They operate on objects of the class.

  • Can access instance variables and other instance methods within the class
  • Can access static variables and methods

Static Methods: Methods that belong to the class itself trather than any instance of the class. Trhey are used for operations taht do not depend on instance-spefific data.

  • Can only directly access other static variables and methods.

Here’s a quick example!

  • Example of an instance method: addMinion()
    • Adds a minion to the list of a villain
    • Parameters: String minon
    • Example call: gru.addMinion(“Kevin”)
  • Second example of an instance method: Villain()
    • Changes instance data
    • Parameters: string Name, String evilPlan
  • Example of a static method: getVillainCount()
    • Returns the total amount of Villain instances
    • No parameters
    • Example call: System.out.println(“There are “ + Villain.getVillainCount() + “ villains in the world.”);

Popcorn hack:

  • Add another static method to the Villain class
  • Keep it minion themed and fun!
import java.util.ArrayList;
import java.util.List;

public class Villain {
    // Instance variables
    public String name;
    public String evilPlan;
    public List<String> minions;
    public static int villainCount = 0;

    // Constructor for name, plan, and minions
    public Villain(String name, String evilPlan) {
        this.name = name;
        this.evilPlan = evilPlan;
        this.minions = new ArrayList<>();
        villainCount++;
    }

    // Instance method to add a minion. LOOK HERE!!
    public void addMinion(String minion) {
        minions.add(minion);
        System.out.println(minion + " has been added to " + name + "'s army.");
    }

    // Instance method to describe the villain. 
    public void describeVillain() {
        System.out.println(name + " is planning to: " + evilPlan);
        System.out.println("They have " + minions.size() + " minions.");
    }

    // Static method to get the total count of villains
    public static int getVillainCount() {
        return villainCount;
    }

     // Static method to recruit minions for all villains
     public static void recruitMinions(List<String> minionsToRecruit) {
        System.out.println("All villains are recruiting new minions: " + minionsToRecruit);
    }
}

public class Main {
    public static void main(String[] args) {
        Villain.villainCount = 0;

        // Create new villains
        Villain gru = new Villain("Gru", "steal the moon!");
        Villain vector = new Villain("Vector", "take over the world with magnitude and direction!");

        System.out.println("=== Adding Minions ===");
        // Create some minions
        gru.addMinion("Kevin");
        gru.addMinion("Stuart");
        gru.addMinion("Bob");

        // Create some minions for Vector
        vector.addMinion("Henchman 1");

        System.out.println();

        // Describe the villains and their plans
        System.out.println("=== Villain Descriptions ===");
        gru.describeVillain();
        System.out.println();
        vector.describeVillain();
        System.out.println();

        // Get the total count of villains
        System.out.println("=== Total Villain Count ===");
        System.out.println("There are " + Villain.getVillainCount() + " villains in the world.");

         // Recruit new minions for all villains
         List<String> newMinions = List.of("Jerry", "Phil", "Carl");
         System.out.println();
         System.out.println("=== Recruiting Minions ===");
         Villain.recruitMinions(newMinions);
    }
}

Main.main(null);
=== Adding Minions ===
Kevin has been added to Gru's army.
Stuart has been added to Gru's army.
Bob has been added to Gru's army.
Henchman 1 has been added to Vector's army.

=== Villain Descriptions ===
Gru is planning to: steal the moon!
They have 3 minions.

Vector is planning to: take over the world with magnitude and direction!
They have 1 minions.

=== Total Villain Count ===
There are 2 villains in the world.

=== Recruiting Minions ===
All villains are recruiting new minions: [Jerry, Phil, Carl]

Popcorn hack:

Dr. Nefario is busy assigning work for the minions, and he needs your help to organize his group. Your mission is to write and implement a Java classes for each minion which includes their name, gadgets, personality, and more. Get ready to make Dr. Nefario’s life easier and keep the minions organized!

import java.util.ArrayList;
import java.util.List;

class Minion {
    // instance variables
    private String name;
    private String personality;
    private List<String> gadgets;
    private String assignedTask;

    // constructor
    public Minion(String name, String personality) {
        this.name = name;
        this.personality = personality;
        this.gadgets = new ArrayList<>();
        this.assignedTask = "No task assigned"; // default task
    }

    // methid to add gadget
    public void addGadget(String gadget) {
        gadgets.add(gadget);
        System.out.println(name + " has been equipped with the " + gadget + ".");
    }

    // method to assign= task
    public void assignTask(String task) {
        assignedTask = task;
        System.out.println(name + " is now working on: " + task);
    }

    // method to display minion's details
    public void displayDetails() {
        System.out.println("Minion Name: " + name);
        System.out.println("Personality: " + personality);
        System.out.println("Gadgets: " + gadgets);
        System.out.println("Assigned Task: " + assignedTask);
        System.out.println();
    }
}

public class DrNefarioLab {
    public static void main(String[] args) {
        // Create some minions
        Minion kevin = new Minion("Kevin", "Playful");
        Minion stuart = new Minion("Stuart", "Lazy");
        Minion bob = new Minion("Bob", "Curious");

        // Equip them with gadgets
        kevin.addGadget("Fart Gun");
        stuart.addGadget("Shrink Ray");
        bob.addGadget("Banana Blaster");

        // Assign tasks
        kevin.assignTask("Build the moon shrinker device.");
        stuart.assignTask("Test the shrink ray.");
        bob.assignTask("Guard the secret base.");

        // Display details of each minion
        System.out.println("=== Minion Details ===");
        kevin.displayDetails();
        stuart.displayDetails();
        bob.displayDetails();
    }
}

DrNefarioLab.main(null);

Kevin has been equipped with the Fart Gun.
Stuart has been equipped with the Shrink Ray.
Bob has been equipped with the Banana Blaster.
Kevin is now working on: Build the moon shrinker device.
Stuart is now working on: Test the shrink ray.
Bob is now working on: Guard the secret base.
=== Minion Details ===
Minion Name: Kevin
Personality: Playful
Gadgets: [Fart Gun]
Assigned Task: Build the moon shrinker device.

Minion Name: Stuart
Personality: Lazy
Gadgets: [Shrink Ray]
Assigned Task: Test the shrink ray.

Minion Name: Bob
Personality: Curious
Gadgets: [Banana Blaster]
Assigned Task: Guard the secret base.