Tutorials

Java OOP Tutorial

All Tutorials Learning Tools Login

Java OOP Tutorial · Chapter 5 of 10

Methods

Give objects useful behavior.

Methods encapsulate actions such as introduce() and displayProfile().

Keep methods focused on one job.

Method sample Try it Yourself »
public class Main {
    public static void main(String[] args) {
        Student student = new Student("Carla Reyes", "BSCS");
        student.introduce();
        student.displayProfile();
    }
}
Student.java
public class Student {
    private String name;
    private String course;

    public Student(String name, String course) {
        this.name = name;
        this.course = course;
    }

    public String getName() {
        return name;
    }

    public String getCourse() {
        return course;
    }

    public void introduce() {
        System.out.println("Hello, I am " + name + " from " + course + ".");
    }

    public void displayProfile() {
        System.out.println("Name: " + name);
        System.out.println("Course: " + course);
    }
}

Classroom Tips

  • Name methods with verbs.
  • Avoid giant methods that do everything.