Friday 23 June 2017

Java Methods

Methods:

A method is a set of code which is referred to by name and can be called (invoked) at any point in a program simply by utilizing the method's name. Think of a method as a subprogram that acts on data and often returns a value.

Method definition consists of a method header and a method body. The same is shown in the following syntax −

Syntax:


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 − Method may return a value.
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.


Each method has its own name. When that name is encountered in a program, the execution of the program branches to the body of that method. When the method is finished, execution returns to the area of the program code from which it was called, and the program continues on to the next line of code.

Good programmers write in a modular fashion which allows for several programmers to work independently on separate concepts which can be assembled at a later date to create the entire project. The use of methods will be our first step in the direction of modular programming.

Methods are time savers, in that they allow for the repetition of sections of code without retyping the code. In addition, methods can be saved and utilized again and again in newly developed programs.

You are using methods when you use:


System.out.print( ) and System.out.println( )


void Keyword:

The void keyword allows us to create methods which do not return a value. In case we want to create a method which does not return any value then the return type should be void but not left empty.

Main Method:

This is very important method in a Java application. Any Java application must contain a main() method whose signature looks like this,

public static void main(String[] args){
      .....
}

A Java program needs to start its execution somewhere. A Java program starts by executing the main method of some class. You can choose the name of the class to execute, but not the name of the method. The method must always be called main. Here is how the main method declaration looks when located inside the Java class declaration; 

public class MyClass {
 public static void main(String[] args) {
 }
}

The three keywords public, static and void have a special meaning which is,

public - The main method is called by the JVM to run the method which is outside the scope of the project therefore the access specifier has to be public to permit a call from anywhere outside the application.

static - When the JVM makes a call to the main method there is no object that exists for the class being called therefore it has to have static method to allow invocation from class.

void - Java is a platform independent language, therefore if it returns some value, then the value may have a different meaning between different platforms so unlike C it can not assume a behavior of returning value to the operating system.
After the three keywords you have the method name.

After the method name comes first a left parenthesis, and then a list of parameters. A main method must always take an array of String objects. 

Types of Methods:

There are two basic types of methods:

Built-in: Build-in methods are part of the compiler package, such as System.out.println( ) and System.exit(0).

User-defined: User-defined methods are created by you, the programmer. These methods take-on names that you assign to them and perform tasks that you create.

How to invoke (call) a method (method invocation):

When a method is invoked (called), a request is made to perform some action, such as setting a value, printing statements, returning an answer, etc. The code to invoke the method contains the name of the method to be executed and any needed data that the receiving method requires. The required data for a method are specified in the method's parameter list.



Consider this example:

public class Student {

 static int regNo = 12345;

 public static void getStudentAge(int age) {
  System.out.println("Age: " + age);
 }

 public static void getStudentName() {
  System.out.println("Name: XYZ");
 }

 public static void main(String[] args) {
  getStudentAge(20);
  getStudentName();
 }
}

Output:
Age: 20
Name: XYZ

The method name is getStudentAge() and getStudentName() which are defined in the same class Student. Since we are calling both the methods with their declared name one after one in main method, first getStudentAge() will be executed, when finished getStudentName() starts to execute.


Passing Parameters(arguments):

When a method is expecting any arguments is to be passed, then you must pass those arguments to that method These should be in the same order and same type as their respective parameters in the method specification.

In above example method getStudentAge is expecting a parameter, so the caller must send the parameter to that method when calling, like getStudentAge(20). If in case same method is expecting a String as a parameter than a string value should be sent.


Most importantly we can create 2 types of methods.
  • Static Methods
  • Instance Methods

Static Methods:

Static methods are which have the static modifier in their declarations.

public static void getStudentAge() {
    ....
}

Static method should be invoked with the class name, without the need for creating an instance of the class, as in,

ClassName.methodName(args);

If you observe above example properly we are calling the methods without using the class name Student. But it should have been called like, 

Student.getStudentAge(20);

We have not used the class name because it's in the same class. If a static method is available in the same class or in the super class in case inheritance, then that method can be accessed directly with the method name.

But what if a static method is not in the calling class?


If a static method is not available in the calling class in case you are not extending(inheriting) it should be invoked with the class name, without the need for creating an instance of the class, as in,



ClassName.methodName(args);

Consider below example for this case:

class  Student{

 public static void getStudentAge(int age) {
  System.out.println("Age: " + age);
 }
}

public class School{
 public static void getRegNo() {
  System.out.println("Reg: 12345");
 }

 public static void main(String[] args) {
  getRegNo();
  Student.getStudentAge(20);//Invoking the method using class name as 
                                          //it is located in another class
 }
}
Output:
Age: 20 Reg: 12345


Instance Methods:

If it's not a static method then it's an instance method.
Instance method are methods which require an object of its class to be created before it can be called. To invoke a instance method, we have to create an Object of the class in within which it defined.

Consider the same example above, in case static is not used to declare the methods.


class  Student{

 public  void getStudentAge(int age) {
  System.out.println("Age: " + age);
 }
}

public class School{
 public  void getRegNo() {
  System.out.println("Reg: 12345");
 }

 public static void main(String[] args) {
  //Create object for School class to access it's instance methods
  School school = new School();
  school.getRegNo();
  
  //Create object for Student class to access it's instance methods
  Student student = new Student();
  student.getStudentAge(20);
 }
}
Output:
Age: 20 Reg: 12345

In above example getStudentAge()  is created as an instance method thus we created an object for the class Student in which the method exists and accessed in another class in a main method. 

But if observe properly, we are also accessing the method getRegNo() which is in the same calling class School and we are creating an object for that class in order to access it. 

But in case of static method within the same calling class we were accessing directly with name. It's because we cannot access instance variables or methods in a static method without creating an object of the class in which instance method exists. Here we are trying to access getRegNo() instance method within a static main method, so we have to create an object to access it.

You can access any instance methods directly with it's name without creating an object of it's class only in another instance method of class assuming both are in same class or you are accessing a instance method of a superclass in a subclass instance method.

Summary:
  • If a static method is not available in the calling class in case you are not extending(inheriting) it should be invoked with the class name, without the need for creating an instance of the class.
  • If a static method is available in the same class or in the super class in case inheritance, then that method can be accessed directly with the method name.
  • We cannot access instance variables or methods in a static method without creating an object of the class in which instance method exists
  • You can access any instance methods directly with it's name without creating an object of it's class only in another instance method of class assuming both are in same class or you are accessing a instance method of a superclass in a subclass instance method.
  • You can access any static method in an instance method directly with it's name in case it's available in the same class or superclass. If static method is in another class it should be accessed with it's class name assuming the class is not a superclass.

No comments:

Post a Comment