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 typemethod_name, and parameters list.

Syntax

Use the below syntax to declare a Java class method:

publicclass class_name {
  modifier returnType nameOfMethod(ParameterList){// 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 −

classUtil{/** the snippet returns the minimum between two numbers */publicintminimum(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 −

packagecom.tutorialspoint;classUtil{publicintminimum(int n1,int n2){int min;if(n1 > n2)
         min = n2;else
         min = n1;return min;}}publicclassTester{publicstaticvoidmain(String[] args){int a =11;int b =6;Util util =newUtil();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.
classStudent{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.
classStudent{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.

packagecom.tutorialspoint;publicclassTester{// Instance variable numint num =10;Tester(){System.out.println("This is an example program on keyword this");}Tester(int num){// Invoking the default constructorthis();// Assigning the local variable num to the instance variable numthis.num = num;}publicvoidgreet(){System.out.println("Hi Welcome to Tutorialspoint");}publicvoidprint(){// Local variable numint num =20;// Printing the local variableSystem.out.println("value of local variable num is : "+num);// Printing the instance variableSystem.out.println("value of instance variable num is : "+this.num);// Invoking the greet method of a classthis.greet();}publicstaticvoidmain(String[] args){// Instantiating the classTester obj1 =newTester();// Invoking the print method
      obj1.print();// Passing a new value to the num variable through parametrized constructorTester obj2 =newTester(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:

publicclassMain{// Creating a static methodstaticvoidfun1(){System.out.println("fun1: This is a static method.");}// Creating a public methodpublicvoidfun2(){System.out.println("fun2: This is a public method.");}// The main() methodpublicstaticvoidmain(String[] args){// Accessing static method through the classfun1();// Creating an object of the Main classMain obj =newMain();// 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 −

protectedvoidfinalize(){// 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.


Comments

Leave a Reply

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