Java Class Methods

🔹 Java Class Methods

Class methods are functions defined inside a class that describe the behavior or actions of objects. They operate on class attributes or perform specific tasks.


✅ 1. Method Syntax

modifier returnType methodName(parameters) {
// method body
return value; // if returnType is not void
}
  • modifier → public, private, static, etc.

  • returnType → data type of value returned (void if nothing is returned)

  • methodName → name of the method

  • parameters → optional input values


✅ 2. Example 1: Instance Method

class Car {
String brand;
int year;

// Instance method
void displayInfo() {
System.out.println("Brand: " + brand + ", Year: " + year);
}
}

public class Main {
public static void main(String[] args) {
Car car1 = new Car();
car1.brand = "Toyota";
car1.year = 2022;
car1.displayInfo(); // Calling instance method

Car car2 = new Car();
car2.brand = "Honda";
car2.year = 2023;
car2.displayInfo();
}
}

📌 Output:

Brand: Toyota, Year: 2022
Brand: Honda, Year: 2023

Instance methods operate on instance variables and require objects to be called.


✅ 3. Example 2: Static Method

class MathOperations {
static int add(int a, int b) { // static method
return a + b;
}
}

public class Main {
public static void main(String[] args) {
int sum = MathOperations.add(5, 10); // No object needed
System.out.println("Sum = " + sum);
}
}

📌 Output:

Sum = 15

Static methods belong to the class, not the object, and can be called using the class name.


✅ 4. Example 3: Method with Parameters and Return Value

class Calculator {
int multiply(int a, int b) { // instance method
return a * b;
}
}

public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator();
int product = calc.multiply(4, 5); // passing parameters
System.out.println("Product = " + product);
}
}

📌 Output:

Product = 20

✅ 5. Example 4: Method Calling Another Method

class Person {
String name;

void greet() {
printName();
System.out.println("Welcome!");
}

void printName() {
System.out.println("Hello, " + name);
}
}

public class Main {
public static void main(String[] args) {
Person p = new Person();
p.name = "Alice";
p.greet();
}
}

📌 Output:

Hello, Alice
Welcome!

✅ 6. Key Points About Class Methods

Feature Instance Method Static Method
Belongs to Object Class
Access instance variables? Yes No (only static variables)
Call syntax object.method() Class.method()
Can be overridden Yes No (cannot override static methods)
  • Methods define object behavior.

  • Instance methods need objects; static methods do not.

  • Methods can have parameters and return values.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *