Java Class Methods

Java Class Methods

Methods are blocks of code within a class that perform a specific task. They define the behavior of an object.

You've already seen one method, the main() method, which is the entry point for the application. Now, let's create our own.


Instance Methods vs. Static Methods

There are two main types of methods in Java:


1. Instance Methods

An instance method is declared without the static keyword. It operates on an object's individual data (its attributes).

Instance Method Example

public class Dog {
  String name;

// This is an instance method public void bark() { System.out.println(name + " says: Woof!"); }

public static void main(String[] args) { // Create an object Dog myDog = new Dog(); myDog.name = "Buddy"; // Call the instance method on the object myDog.bark(); } }


2. Static Methods

A static method is declared with the static keyword. Since it doesn't belong to a specific object, it cannot access instance attributes (like name in the Dog class). Static methods are often used for utility functions.

The main() method is static because the JVM needs to call it to start the program without first creating an object.

Static Method Example

public class Main {

// A static method static void myStaticMethod() { System.out.println("Static methods can be called without creating objects"); }

// A public (instance) method public void myPublicMethod() { System.out.println("Public methods must be called on objects"); }

public static void main(String[] args) { myStaticMethod(); // Call the static method directly Main myObj = new Main(); // Create an object of Main myObj.myPublicMethod(); // Call the public method on the object } }