Java Tutorial

Java Control Statements

Object Oriented Programming

Java Built-in Classes

Java File Handling

Java Error & Exceptions

Java Multithreading

Java Synchronization

Java Networking

Java Collections

Java Interfaces

Java Data Structures

Java Collections Algorithms

Advanced Java

Java Miscellaneous

Java APIs & Frameworks

Java Class References

Java Useful Resources

Java - Class Methods



Java Class Methods

The class methods are methods that are declared within a class. They perform specific operations and can access, modify the class attributes.

Creating (Declaring) Java Class Methods

Class methods declaration is similar to the user-defined methods declaration except that class methods are declared within a class.

The class methods are declared by specifying the access modifier followed by the return type, method_name, and parameters list.

Syntax

Use the below syntax to declare a Java class method:

public class class_name {
  modifier returnType nameOfMethod(Parameter List) {
    // method body
  }
}

The syntax shown above includes −

  • modifier − It defines the access type of the method and it is optional to use.

  • returnType − The returns data type of the class method.

  • nameOfMethod − This is the method name. The method signature consists of the method name and the parameter list.

  • Parameter List − The list of parameters, it is the type, order, and number of parameters of a method. These are optional, method may contain zero parameters.

  • method body − The method body defines what the method does with the statements.

Example

Here is the source code of the above defined method called minimum(). This method takes two parameters n1 and n2 and returns the minimum between the two −

class Util {
  /** the snippet returns the minimum between two numbers */
  public int minimum(int n1, int n2) {
    int min;
    if (n1 > n2)
      min = n2;
    else
      min = n1;

    return min;
  }
}

Accessing Java Class Methods

To access a class method (public class method), you need to create an object first, then by using the object you can access the class method (with the help of dot (.) operator).

Syntax

Use the below syntax to access a Java public class method:

object_name.method_name([parameters]);

Example

Following is the example to demonstrate how to define class method and how to access it. Here, We've created an object of Util class and call its minimum() method to get minimum value of given two numbers −

package com.tutorialspoint;

class Util {
   public int minimum(int n1, int n2) {
      int min;
      if (n1 > n2)
         min = n2;
      else
         min = n1;

      return min; 
   }
}
public class Tester {
   
   public static void main(String[] args) {
      int a = 11;
      int b = 6;

      Util util = new Util();
	  
      int c = util.minimum(a, b);
      System.out.println("Minimum Value = " + c);
   }
}

Output

Minimum value = 6

this Keyword in Java Class Methods

this is a keyword in Java which is used as a reference to the object of the current class, with in an instance method or a constructor. Using this you can refer the members of a class such as constructors, variables and methods.

Note − The keyword this is used only within instance methods or constructors

In general, the keyword this is used to −

  • Differentiate the instance variables from local variables if they have same names, within a constructor or a method.

class Student {
   int age;   
   Student(int age) {
      this.age = age;	
   }
}
  • Call one type of constructor (parametrized constructor or default) from other in a class. It is known as explicit constructor invocation.

class Student {
   int age
   Student() {
      this(20);
   }
   
   Student(int age) {
      this.age = age;	
   }
}

Example: Using this Keyword in Java Class Methods

Here is an example that uses this keyword to access the members of a class. Copy and paste the following program in a file with the name, Tester.java.

package com.tutorialspoint;

public class Tester {
   // Instance variable num
   int num = 10;
	
   Tester() {
      System.out.println("This is an example program on keyword this");	
   }

   Tester(int num) {
      // Invoking the default constructor
      this();
      
      // Assigning the local variable num to the instance variable num
      this.num = num;	   
   }
   
   public void greet() {
      System.out.println("Hi Welcome to Tutorialspoint");
   }
      
   public void print() {
      // Local variable num
      int num = 20;
      
      // Printing the local variable
      System.out.println("value of local variable num is : "+num);
      
      // Printing the instance variable
      System.out.println("value of instance variable num is : "+this.num);
      
      // Invoking the greet method of a class
      this.greet();     
   }
   
   public static void main(String[] args) {
      // Instantiating the class
      Tester obj1 = new Tester();
      
      // Invoking the print method
      obj1.print();
	  
      // Passing a new value to the num variable through parametrized constructor
      Tester obj2 = new Tester(30);
      
      // Invoking the print method again
      obj2.print(); 
   }
}

Output

This is an example program on keyword this 
value of local variable num is : 20
value of instance variable num is : 10
Hi Welcome to Tutorialspoint
This is an example program on keyword this 
value of local variable num is : 20
value of instance variable num is : 30
Hi Welcome to Tutorialspoint

Public Vs. Static Class Methods

There are two types of class methods public and static class method. The public class methods are accessed through the objects whereas, the static class methods are accessed are accesses without an object. You can directly access the static methods.

Example

The following example demonstrates the difference between public and static class methods:

public class Main {
  // Creating a static method
  static void fun1() {
    System.out.println("fun1: This is a static method.");
  }

  // Creating a public method
  public void fun2() {
    System.out.println("fun2: This is a public method.");
  }

  // The main() method
  public static void main(String[] args) {
    // Accessing static method through the class
    fun1();

    // Creating an object of the Main class
    Main obj = new Main();
    // Accessing public method through the object
    obj.fun2();
  }
}

Output

fun1: This is a static method.
fun2: This is a public method.

The finalize( ) Method

It is possible to define a method that will be called just before an object's final destruction by the garbage collector. This method is called finalize( ), and it can be used to ensure that an object terminates cleanly.

For example, you might use finalize( ) to make sure that an open file owned by that object is closed.

To add a finalizer to a class, you simply define the finalize( ) method. The Java runtime calls that method whenever it is about to recycle an object of that class.

Inside the finalize( ) method, you will specify those actions that must be performed before an object is destroyed.

The finalize( ) method has this general form −

protected void finalize( ) {
   // finalization code here
}

Here, the keyword protected is a specifier that prevents access to finalize( ) by code defined outside its class.

This means that you cannot know when or even if finalize( ) will be executed. For example, if your program ends before garbage collection occurs, finalize( ) will not execute.

Advertisements