04 Java - Methods

What is Method?

  • Method is used to perform certain task.

  • It's a collection of instruction that perform some specific task

  • It can be used to bring the code readability and re-usability.

public class Calculation {

    public int sum(int val1, int val2){
        int total = val1 + val2;
        //doing some logging stuff
        System.out.println("addition of val1 and val2 is "+total);
        return total;
    }

    public int getPriceOfPen(){
        int capPrice = 2;
        int penBodyPrice = 5;

        int discountedPrice = sum(capPrice,penBodyPrice-1);
        System.out.println(discountedPrice);

        int totalPenPrice = sum(capPrice,penBodyPrice);
        return totalPenPrice;
    }
}

How to declare a method?

public static sum(int a, int b) throws Exception{
//method body
}

/*
public - access specifier
static -
sum - method name
int a, int b - parameters

*/

Access Specifiers

  • Public: can be access through any class in any package

  • Private: can be access by methods only in the same class.

  • Protected: can be access by other classes in same package or other subclasses in different package.

  • Default: If we do not mention anything, then Default access specifier is used by Java. It can be only accessed by classes in same package. (note subclasses in different package cannot access it)

Note:

  • Package: It is a collection of similar classes

  • Subclasses: Children of parent class.

Return Type

  • Method do not reutrn anything use "void"

  • Use Class Name or primitive data types as return type of the method.

    public int sum(int val1, int val2){
        int total = val1 + val2;
        return total;
    }

    public boolean isPresent(int val1){
        return true;
    }

    public void isPresent(int val1){
        return;//not requried
    }

Method Name

  • It should be verb (some kind of action) like getData, sendMessage.

  • Should start with small letter and follow camel case in case of multiple words.

Parameters

  • It's a list of variables that will be used in the method.

  • Parameter list can be blank too.

Types of Method

System Defined Method

  • Methods which are already defined and ready to use in Java like Math.sqrt()

User Defined Method

  • Methods which programmer creates based upon the program necessity.

Overloaded Method (Static binding)

  • More than one method with same name is created in same class.

  • Overloaded methods get differentiated based on the arguments. Return type is not considered.

void getInvoice(){
}

void getInvoice(int a){
}

int getInvoice(String a){
}

// Return type doesn't matter.
/*
int getInvoice(){
}
this doesn't work
*/

Overridden Method (Dynamic binding)

  • Subclass has the same method as the parent class
public class Doctor Person{
    @Override
    public void profession(){
    }
}


public class Doctor Person{
    @Override
    public void profession(){ 
        //Overridden Method 
        //@Override annotation not required but good practice
    }
}

Static Method

  • These methods are associated with the class

  • Can be called just with class name.

  • Static methods cannot access Non Static Instance variables and methods

    • Because non-static instance variables/methods are properties related to objects, static methods are not aware of which object instance variable to utilize.
  • Static method cannot be overridden. (It can be hidden)

  • Static is compile time.

When to declare method static:

  • Methods which do not modify the state of the object can be declared staic.

  • Utility method which do not use any instance variable and compute only on arguments.

Example: Factory deisgn pattern.

Static visualization

Hiding the static methods in subclass

public class Person {
    public static void profession(){
        System.out.println("Searching for profession");
    }
}

public class Doctor extends Person{
}

Person.profession(); //Searching for profession
Doctor.profession(); //Searching for profession
public class Person {
    public static void profession(){
        System.out.println("Searching for profession");
    }
}

public class Doctor extends Person{
    public static void profession(){
        System.out.println("Doctor is my profession");
    }
}

Person.profession(); //Searching for profession
Doctor.profession(); //Doctor is my profession
public class Person {
    public static void profession(){
        System.out.println("Searching for profession");
    }
}

public class Doctor extends Person{
    @Override
    public static void profession(){
        System.out.println("Doctor is my profession");
    }
}

/*
@Override is not possible because static is compile time. 
@Override is dynamic
*/

Final Method

  • Final method can not be overridden in java.

  • Why? final method means its implementation can not be changed. If child class can not change its implementation then no use of overridden.

public class Person {
    public final void profession(){
        System.out.println("Searching for profession");
    }
}


public class Doctor extends Person{

    @Override //Not Possible
    public void profession(){
        System.out.println("Doctor is my profession");
    }
}

Abstract method

  • It is defined only in abstract classes.

  • Only method declaration is done.

  • Its implementation is done in child classes.

public abstract class Person {
    public void profession(){
        System.out.println("Searching for profession");
    }

    public abstract int print();
}

public class Doctor extends Person{
    @Override
    public int print() {
        //some implementation
        return 0;
    }
}

Variable Arguments (VARARGS)

  • Variable number of inputs in the parameter.

  • Only one variable argument can be present in the method.

  • It should be the last argument in the list.

Issue:

public class Calculation {

    public int sum(int val1, int val2){
        int total = val1 + val2;
        return total;
    }

    public int sum(int val1){
        int total = val1;
        return total;
    }

    public int sum(int val1, int val2,int val3){
        int total = val1 + val2 + val3;
        return total;
    }

    public int sum(int val1, int val2,int val3, int val4,int val5,int val6,int val7){
        int total = val1 + val2 + val3+ val4 + val5 + val6+val7;
        return total;
    }
}

using variable args

public class Calculation {

    //Sample - 1
    public int sum(int ...values){
        int total = 0;
        for (int val: values){
            total += val;
        }
        return total;
    }

    //Sample - 2
    public int sum(int a, int ...values){
        int total = a;
        for (int val: values){
            total += val;
        }
        return total;
    }

    //Sample 1 and 2 both are same
    // Hence only one method should be present
    // If not the call will be ambiguous

    //Sample - 3
    public int sum(String action, int ...values){
        System.out.println("Action performing"+action);
        int total = a;
        for (int val: values){
            total += val;
        }
        return total;
    }
}

//usage
Calculation calculation = new Calculation();
calculation.sum(8,8,8);
calculation.sum("add", 993,3783);