Skip to content

Java Methods

Introduction:

Briefly introduce the importance of methods in Java programming and how they contribute to code organization, reusability, and readability.

1. Understanding Java Methods:

  • Definition of methods in Java.
  • Syntax and structure of a method declaration.
  • Access modifiers: public, private, protected, default.
  • public: The public access modifier allows unrestricted access from any other class or package.
    public class MyClass {
        public void publicMethod() {
            System.out.println("This is a public method.");
        }
    }
    

      • private: The private access modifier restricts access to only within the same class. It is often used to encapsulate the internal functionality of a class.

      public class MyClass {
          private int privateField;
      
          private void privateMethod() {
              System.out.println("This is a private method.");
          }
      }
      

      • protected: The protected access modifier allows access within the same package and by subclasses, even if they are in different packages

      public class MyClass {
          protected int protectedField;
      
          protected void protectedMethod() {
              System.out.println("This is a protected method.");
          }
      }
      

      • Default (no modifier): If no access modifier is specified, the default access modifier is applied. It allows access within the same package but not from outside the package.

      class MyClass {
          int defaultField;
      
          void defaultMethod() {
              System.out.println("This is a default (package-private) method.");
          }
      }
      
      

      2. Types of Java Methods:

      • Static methods vs. instance methods.
      public class MethodTypesExample {
          // Static method
          public static void staticMethod() {
              System.out.println("This is a static method.");
          }
      
          // Instance method
          public void instanceMethod() {
              System.out.println("This is an instance method.");
          }
      
          public static void main(String[] args) {
              // Calling static method
              staticMethod(); // Output: This is a static method.
      
              // Creating an object to call instance method
              MethodTypesExample obj = new MethodTypesExample();
              obj.instanceMethod(); // Output: This is an instance method.
          }
      }
      

      • Void methods vs. methods with return types.
      public class ReturnTypeExample {
          // Method with return type
          public int add(int a, int b) {
              return a + b;
          }
      
          // Void method
          public void printMessage(String message) {
              System.out.println(message);
          }
      
          public static void main(String[] args) {
              ReturnTypeExample obj = new ReturnTypeExample();
      
              // Calling method with return type
              int sum = obj.add(5, 7);
              System.out.println("Sum: " + sum); // Output: Sum: 12
      
              // Calling void method
              obj.printMessage("Hello, world!"); // Output: Hello, world!
          }
      }
      

      • Overloaded methods.
      public class OverloadedMethodExample {
          // Overloaded methods
          public int add(int a, int b) {
              return a + b;
          }
      
          public double add(double a, double b) {
              return a + b;
          }
      
          public static void main(String[] args) {
              OverloadedMethodExample obj = new OverloadedMethodExample();
      
              // Calling overloaded methods
              System.out.println("Sum of integers: " + obj.add(5, 7)); // Output: Sum of integers: 12
              System.out.println("Sum of doubles: " + obj.add(3.5, 2.7)); // Output: Sum of doubles: 6.2
          }
      }
      

      • Void methods vs. methods with return types:
      public class ReturnTypeExample {
          // Method with return type
          public int add(int a, int b) {
              return a + b;
          }
      
          // Void method
          public void printMessage(String message) {
              System.out.println(message);
          }
      
          public static void main(String[] args) {
              ReturnTypeExample obj = new ReturnTypeExample();
      
              // Calling method with return type
              int sum = obj.add(5, 7);
              System.out.println("Sum: " + sum); // Output: Sum: 12
      
              // Calling void method
              obj.printMessage("Hello, world!"); // Output: Hello, world!
          }
      }
      

      • Overloaded methods:
      public class OverloadedMethodExample {
          // Overloaded methods
          public int add(int a, int b) {
              return a + b;
          }
      
          public double add(double a, double b) {
              return a + b;
          }
      
          public static void main(String[] args) {
              OverloadedMethodExample obj = new OverloadedMethodExample();
      
              // Calling overloaded methods
              System.out.println("Sum of integers: " + obj.add(5, 7)); // Output: Sum of integers: 12
              System.out.println("Sum of doubles: " + obj.add(3.5, 2.7)); // Output: Sum of doubles: 6.2
          }
      }
      

      • Recursive methods:
      public class RecursiveMethodExample {
          // Recursive method to calculate factorial
          public int factorial(int n) {
              if (n == 0)
                  return 1;
              else
                  return n * factorial(n - 1);
          }
      
          public static void main(String[] args) {
              RecursiveMethodExample obj = new RecursiveMethodExample();
      
              // Calling recursive method
              int result = obj.factorial(5);
              System.out.println("Factorial of 5: " + result); // Output: Factorial of 5: 120
          }
      }
      

      3. Method Overriding and Overloading:

      • Explanation of method overloading.

      Method overloading is a feature in Java that allows a class to have multiple methods with the same name but with different parameters. This provides flexibility and allows developers to use the same method name for different behaviors based on the parameters passed to it. Overloaded methods can have different parameter types, different numbers of parameters, or both.

      public class OverloadingExample {
          // 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;
          }
      
          public static void main(String[] args) {
              OverloadingExample obj = new OverloadingExample();
      
              System.out.println("Sum of two numbers: " + obj.add(5, 7)); // Output: Sum of two numbers: 12
              System.out.println("Sum of three numbers: " + obj.add(3, 6, 9)); // Output: Sum of three numbers: 18
          }
      }
      

      • Explanation of method overriding.

      Method overriding is a feature in Java that allows a subclass to provide a specific implementation of a method that is already provided by its superclass. This allows a subclass to modify the behavior of an existing method in its superclass. Method overriding is used to achieve runtime polymorphism, where the actual method that gets invoked is determined at runtime based on the type of object.

      Example demonstrating method overriding.

      class Animal {
          // Method in the superclass
          public void sound() {
              System.out.println("Animal makes a sound");
          }
      }
      
      class Dog extends Animal {
          // Overriding the sound method in the subclass
          @Override
          public void sound() {
              System.out.println("Dog barks");
          }
      }
      
      public class MethodOverridingExample {
          public static void main(String args[]) {
              Animal animal = new Dog(); // Creating Dog object using Animal reference
              animal.sound(); // Output: Dog barks
          }
      }
      

      4. Java Method Examples:

      • Example 1: Simple method with no parameters and no return type:
      public class SimpleMethodExample {
          // Simple method with no parameters and no return type
          public static void greet() {
              System.out.println("Hello, world!");
          }
      
          public static void main(String[] args) {
              // Calling the greet method
              greet(); // Output: Hello, world!
          }
      }
      

      Example 2: Method with parameters and a return type:

      public class MethodWithParametersExample {
          // Method with parameters and a return type
          public static int add(int a, int b) {
              return a + b;
          }
      
          public static void main(String[] args) {
              // Calling the add method with two parameters
              int sum = add(5, 7);
              System.out.println("Sum: " + sum); // Output: Sum: 12
          }
      }
      

      Example 3: Static method example:

      public class StaticMethodExample {
          // Static method example
          public static double calculateArea(double radius) {
              return Math.PI * radius * radius;
          }
      
          public static void main(String[] args) {
              // Calling the calculateArea method
              double area = calculateArea(3.5);
              System.out.println("Area: " + area); // Output: Area: 38.48451000647496
          }
      }
      

      Example 4: Method overloading example:

      public class MethodOverloadingExample {
          // Method overloading example
          public static int add(int a, int b) {
              return a + b;
          }
      
          public static int add(int a, int b, int c) {
              return a + b + c;
          }
      
          public static void main(String[] args) {
              // Calling the overloaded add method with two parameters
              int sum1 = add(5, 7);
              System.out.println("Sum 1: " + sum1); // Output: Sum 1: 12
      
              // Calling the overloaded add method with three parameters
              int sum2 = add(3, 6, 9);
              System.out.println("Sum 2: " + sum2); // Output: Sum 2: 18
          }
      }
      

      Example 5: Method overriding example:

      class Animal {
          // Method overriding example
          public void sound() {
              System.out.println("Animal makes a sound");
          }
      }
      
      class Dog extends Animal {
          @Override
          public void sound() {
              System.out.println("Dog barks");
          }
      }
      
      public class MethodOverridingExample {
          public static void main(String args[]) {
              Dog dog = new Dog();
              dog.sound(); // Output: Dog barks
          }
      }
      

      Conclusion:

      Summarize the importance of understanding and effectively using methods in Java programming. Encourage readers to practice writing methods and explore more advanced concepts.

      Leave a Reply

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