Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Java Class Methods in Java

Java Class Methods in Java

Class Methods in Java

In Java, class methods (also known as member methods) are functions or operations that belong to a class and can be invoked on instances of that class (or on the class itself if the method is static). Methods are used to define behaviors that the objects of the class can perform or to interact with the class’s attributes.

Class methods are classified into two main types:

  1. Instance Methods (Non-static methods)

  2. Static Methods (Class methods)


1. Instance Methods

Instance methods are associated with specific instances (objects) of a class. They can access both instance variables (non-static variables) and static variables of the class. Instance methods are called using objects of the class.

Syntax of an Instance Method:

<return_type> <method_name>(<parameters>) {    // method body}

Example of an Instance Method:

public class Car {    // Instance variables    String model;    int year;    // Constructor to initialize the instance variables    public Car(String model, int year) {        this.model = model;        this.year = year;    }    // Instance method to display car details    public void displayDetails() {        System.out.println("Model: " + model);        System.out.println("Year: " + year);    }    public static void main(String[] args) {        // Creating an object of the Car class        Car myCar = new Car("Toyota", 2020);        // Calling the instance method using the object        myCar.displayDetails();  // Output: Model: Toyota, Year: 2020    }}

Explanation:

  • The method displayDetails() is an instance method, which means it can only be called on an instance of the Car class (an object).

  • myCar.displayDetails() calls the method to display details of the myCar object.


2. Static Methods

Static methods are associated with the class itself, rather than with instances of the class. They can only access static variables and methods within the class. Static methods are called using the class name or via an object, but the recommended practice is to call them using the class name.

Syntax of a Static Method:

static <return_type> <method_name>(<parameters>) {    // method body}

Example of a Static Method:

public class Calculator {    // Static method for adding two numbers    public static int add(int a, int b) {        return a + b;    }    // Static method for multiplying two numbers    public static int multiply(int a, int b) {        return a * b;    }    public static void main(String[] args) {        // Calling static methods using the class name        int sum = Calculator.add(10, 20);  // Output: 30        int product = Calculator.multiply(5, 6);  // Output: 30        // Printing the results        System.out.println("Sum: " + sum);        System.out.println("Product: " + product);    }}

Explanation:

  • The add() and multiply() methods are static methods and are called using the class name (Calculator.add() and Calculator.multiply()).

  • Static methods cannot access non-static instance variables or methods, but they can access other static members of the class.


Key Differences Between Instance and Static Methods

FeatureInstance MethodsStatic Methods
AssociationAssociated with an object (instance of the class).Associated with the class itself.
Access to MembersCan access both instance and static variables.Can only access static variables and methods.
InvocationInvoked using an object of the class.Invoked using the class name (preferred) or an object.
Memory UsageEach object has its own copy of instance methods.There is only one copy of static methods, shared by all instances.

Method Return Types

Methods in Java can return a value of any data type (e.g., int, String, boolean, or any custom type). If a method doesn't need to return any value, you can use the void return type.

Example of Method with Return Type:

public class MathOperations {    // Method with int return type    public int subtract(int a, int b) {        return a - b;    }    // Method with String return type    public String greet(String name) {        return "Hello, " + name + "!";    }    public static void main(String[] args) {        MathOperations math = new MathOperations();        // Calling the method and capturing the return value        int difference = math.subtract(10, 5);  // Output: 5        String greeting = math.greet("Alice");  // Output: Hello, Alice!        // Printing the results        System.out.println("Difference: " + difference);        System.out.println(greeting);    }}

Output:

Difference: 5Hello, Alice!

Method Overloading in Java

In Java, you can have multiple methods with the same name in the same class, as long as they have different parameter lists (either in type or number). This is called method overloading.

Example of Method Overloading:

public class OverloadExample {    // Method to add two integers    public int add(int a, int b) {        return a + b;    }    // Overloaded method to add three integers    public int add(int a, int b, int c) {        return a + b + c;    }    // Overloaded method to add two doubles    public double add(double a, double b) {        return a + b;    }    public static void main(String[] args) {        OverloadExample example = new OverloadExample();        // Calling overloaded methods        System.out.println("Sum of two integers: " + example.add(2, 3));  // Output: 5        System.out.println("Sum of three integers: " + example.add(2, 3, 4));  // Output: 9        System.out.println("Sum of two doubles: " + example.add(2.5, 3.5));  // Output: 6.0    }}

Output:

Sum of two integers: 5Sum of three integers: 9Sum of two doubles: 6.0

Method Parameter Types

Methods in Java can accept parameters (input values). These parameters can be of any type, including primitive types (int, double, etc.) or reference types (String, arrays, objects, etc.).

Example of Method with Parameters:

public class Greeting {    // Method with parameters    public void greet(String name, int age) {        System.out.println("Hello, " + name + "! You are " + age + " years old.");    }    public static void main(String[] args) {        Greeting greeting = new Greeting();        greeting.greet("John", 30);  // Output: Hello, John! You are 30 years old.    }}

Output:

Hello, John! You are 30 years old.

Method Invocation (Calling Methods)

  1. Instance Method Invocation: Called using an object of the class.

    ClassName objectName = new ClassName();objectName.methodName(arguments);
  2. Static Method Invocation: Called using the class name (recommended) or through an object.

    ClassName.methodName(arguments);

Method Scope and Access Modifiers

  • private: The method is accessible only within the class.

  • default (no modifier): The method is accessible within the same package.

  • protected: The method is accessible within the same package and by subclasses.

  • public: The method is accessible from any other class.


Summary

  • Instance Methods: Belong to an object and can access both instance and static members.

  • Static Methods: Belong to the class itself and can only access static members.

  • Methods in Java can return values of any type and can be overloaded based on different parameter types or counts.

  • Access Modifiers control the visibility of methods across classes.

Let me know if you need more examples or have further questions! ?

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql