Details the use of methods in Java object oriented programming

  • 2020-05-05 11:15:24
  • OfStack

An Java method is a combination of statements to perform an operation. For example, when you call the System.out.println method, the system actually executes a lot of statements to output information on the console.

Now you'll learn how to create your own methods, which can have or have no return value, which can have arguments, which can have no arguments, which can have the same method name for overloaded methods, and which take advantage of abstract methods in programming.

create method
we explain the syntax of the method with the following example:


public static int funcName(int a, int b) {
 // body
}

Here

public static: modifier int: return value type funcName: function name a, b: formal parameters int a,int b: parameter column

Methods also contain procedures or functions.

Procedures: they do not return the value function: they return the value

The definition of a method includes the method head and the method body. As shown below:


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

The syntax above includes

modifier: he defines the access type of the method, which is optional. returnType: it is possible for a method to return a value. nameOfMethod: this is the name of the method. The method signature includes the method name and a list of parameters. Parameter List: parameter list, which is a collection of the order, type, and number of parameters. These are optional, although methods can have no arguments. Method body: the method body defines what the method is used to do.

Sample

This is the method max() defined above, which takes two parameters num1 and num2 and returns the maximum value between them.


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

  return min; 
}

The method calls
To use a method,
must be called. There are two ways to call a method, one with a return value and one without.

Calling a method is simple. When a program needs to call a method, the controller moves to the called method, and the method returns two conditions to the caller:

Returns an execution statement to the end of the method

Using the method that returns void as a call statement, let me look at the following example:


System.out.println("wiki.jikexueyuan.com!");

The return value of this method can be understood by the following example:


int result = sum(6, 9);

Sample

The following example shows how to define a method and call it:


public class ExampleMinNumber{

  public static void main(String[] args) {
   int a = 11;
   int b = 6;
   int c = minFunction(a, b);
   System.out.println("Minimum Value = " + c);
  }

  /** returns the minimum of two numbers */
  public static int minFunction(int n1, int n2) {
   int min;
   if (n1 > n2)
     min = n2;
   else
     min = n1;

   return min; 
  }
}

The result is


Minimum value = 6

keyword void
The
keyword void allows us to create a method that returns no value. Here we create an void method methodRankPoints in the next example. This method has no return value type. The void method must declare methodRankPoints(255.7); The Java statement ends with a semicolon, as shown below:


public class ExampleVoid {

  public static void main(String[] args) {
   methodRankPoints(255.7);
  }

  public static void methodRankPoints(double points) {
   if (points >= 202.5) {
     System.out.println("Rank:A1");
   }
   else if (points >= 122.4) {
     System.out.println("Rank:A2");
   }
   else {
     System.out.println("Rank:A3");
   }
  }
}

This produces the following result:


Rank:A1

passes the parameter
by value
arguments must be passed when a function is called. And their order must be the same as the order of arguments they created. Parameters can be passed by value or reference.

Passing an argument by value means that the argument to the calling method is passed to the argument by the argument value.

Sample

The following program gives an example to show passing parameters by value. The parameter value does not change after the method is called.


public class swappingExample {

  public static void main(String[] args) {
   int a = 30;
   int b = 45;

   System.out.println("Before swapping, a = " +
             a + " and b = " + b);

   // Invoke the swap method
   swapFunction(a, b);
   System.out.println("\n**Now, Before and After swapping values will be same here**:");
   System.out.println("After swapping, a = " +
             a + " and b is " + b);
  }

  public static void swapFunction(int a, int b) {

   System.out.println("Before swapping(Inside), a = " + a
              + " b = " + b);
   // Swap n1 with n2
   int c = a;
   a = b;
   b = c;

   System.out.println("After swapping(Inside), a = " + a
              + " b = " + b);
  }
}

This will result in


modifier returnType nameOfMethod (Parameter List) {
 // method body
}
0

Overloading
for the method is an overload of a method when it has two or more methods with the same name but different parameters. It's different from covering. Overrides are methods with the same name, type, and number of arguments.

Let's consider the previous example of finding the smallest integer. If we want to find the smallest number in a floating point, we need to take advantage of the method overloading to create two or more methods with the same function name but different arguments.

The following example explains:


public class ExampleOverloading{

  public static void main(String[] args) {
   int a = 11;
   int b = 6;
   double c = 7.3;
   double d = 9.4;
   int result1 = minFunction(a, b);
   // same function name with different parameters
   double result2 = minFunction(c, d);
   System.out.println("Minimum Value = " + result1);
   System.out.println("Minimum Value = " + result2);
  }

 // for integer
  public static int minFunction(int n1, int n2) {
   int min;
   if (n1 > n2)
     min = n2;
   else
     min = n1;

   return min; 
  }
  // for double
  public static double minFunction(double n1, double n2) {
   double min;
   if (n1 > n2)
     min = n2;
   else
     min = n1;

   return min; 
  }
}

This will result in


Minimum Value = 6
Minimum Value = 7.3

Overloading methods makes the program easy to read. In this case, the two methods have the same name but different parameters. Produces the smallest number of integer and floating-point types as the result of a program run.

USES the command-line argument
sometimes you want to pass arguments before the program runs. This can be done by passing command-line arguments to the main function.

On the command line, when a program file is to be executed, a command line argument appears immediately after the file name. Taking command line arguments is easy in Java programs. They are passed into the main function character array.

Sample

The following example shows a program that outputs all command line arguments:


modifier returnType nameOfMethod (Parameter List) {
 // method body
}
3

The program is executed by the following method:


modifier returnType nameOfMethod (Parameter List) {
 // method body
}
4

This will produce the following result:


modifier returnType nameOfMethod (Parameter List) {
 // method body
}
5

constructor
this is a simple example of using a constructor :


modifier returnType nameOfMethod (Parameter List) {
 // method body
}
6

You can instantiate an object by calling the constructor in the following way:


public class ConsDemo {

  public static void main(String args[]) {
   MyClass t1 = new MyClass();
   MyClass t2 = new MyClass();
   System.out.println(t1.x + " " + t2.x);
  }
}

Typically, you will need a constructor to accept one or more arguments. Passing arguments is the same as for the normal method described above, which lists the arguments after the constructor name.

Sample

This is a simple example of using a constructor :


// A simple constructor.
class MyClass {
  int x;

  // Following is the constructor
  MyClass(int i ) {
   x = i;
  }
}

You can instantiate an object by calling the constructor in the following way:


modifier returnType nameOfMethod (Parameter List) {
 // method body
}
9

This will result in


10 20

variable length parameter
JDK 1.5 allows you to pass the same type of argument with variable length. Declare as follows:


typeName... parameterName

When you declare a method, you specify the parameter type before the ellipsis, and you can only have one variable length parameter, and the variable length parameter must be the last of all parameters.

Sample


public class VarargsDemo {

  public static void main(String args[]) {
   // Call method with variable args 
   printMax(34, 3, 3, 2, 56.5);
   printMax(new double[]{1, 2, 3});
  }

  public static void printMax( double... numbers) {
  if (numbers.length == 0) {
   System.out.println("No argument passed");
   return;
  }

  double result = numbers[0];

  for (int i = 1; i < numbers.length; i++)
   if (numbers[i] > result)
   result = numbers[i];
   System.out.println("The max value is " + result);
  }
}

This will produce the following result:


The max value is 56.5
The max value is 3.0

finalize() method
you can define a method that is called only before it is destroyed by the garbage collector. This method is called the finalize() method, and it can also be used to ensure that an object is cleanly cleared.

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

To add a finalizer to a class, you simply define the finalize() method. This method is called when Java wants to reclaim an object of the class.

In the finalize() method, you specify some behavior that must be done before the object is destroyed.

The finalize() method generally looks like this:


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

Here, the keyword protected is used to ensure that code outside the class cannot access the finalize() method.

This means you don't know when finalize() will be executed. For example, if your program ends before the garbage collector occurs, the finalize() method will not be executed.

generic method:
The
java generic method is widely used when the method return value is a container class object.


public static List<T> find(Class<T> clazz,String userId){
   ....
}

In general, when writing an java generic method, the return value type and at least one parameter type should be generic, and the types should be consistent. If only one of the return value types or parameter types USES a generic, the use of this generic method is greatly limited, almost to the point where it is not.

The following sections focus on the use of two very similar java generic methods and the differences between them.
The first:


  public static <T extends CommonService> T getService(Class<T> clazz) {
    T service = (T) serviceMap.get(clazz.getName());
    if (service == null) {
      service = (T) ServiceLocator.getService(clazz.getName());
      serviceMap.put(clazz.getName(), service);
    }
    return service;
  }

Second:


  public static <T> T getService(Class<? extends CommonService> clazz) {
    T service = (T) serviceMap.get(clazz.getName());
    if (service == null) {
      service = (T) ServiceLocator.getService(clazz.getName());
      serviceMap.put(clazz.getName(), service);
    }
    return service;
  }

Here is the class where the generic method resides:


public abstract class CommonService {
  private static HashMap<String, CommonService> serviceMap = new HashMap<String, CommonService>();
  // Here is the generic method definition 
  .
  .
  .
}

The only difference between these two generic methods is that the method signatures are different, and the method bodies are identical, so what's the difference between them?
Let's use them and see the difference.
For the first generic method:


public class Main {
  public static void main(String[] args) {
    NoticeService noticeService=CommonService.getService(NoticeService.class);// Use the first generic method correctly and there will be no compilation errors. 
    NoticeService noticeService=CommonService.getService(UserService.class);// Incorrect use of the first generic method results in compilation errors. 
    
  }
}

For the second generic method:


public class Main {
  public static void main(String[] args) {
    NoticeService noticeService=CommonService.getService(NoticeService.class);// The second generic method is used correctly, with no compilation errors, correct logic, and no exceptions at run time. 
    NoticeService noticeService=CommonService.getService(UserService.class);// Incorrect use of the second generic method, will not appear compilation errors, but the logic is not correct, will run an exception, dangerous! 
 
  }
}

Now you know the difference between these two very similar generic methods?

The first generic method: the return value and the parameter value are of the same type. The second generic method: the return value and the parameter value are not of the same type, so be careful or avoid using them.

Related articles: