Home > Net >  Why do we initiate an object inside main function
Why do we initiate an object inside main function

Time:04-10

class MergeSort {

    // Merge two subarrays L and M into arr
    void merge(int arr[], int p, int q, int r) {
    }
  
    // Divide the array into two subarrays, sort them and merge them
    void mergeSort(int arr[], int l, int r) {
    }
  
    // Print the array
    static void printArray(int arr[]) {
    }
  
    // Driver program
    public static void main(String args[]) {
      int arr[] = { 6, 5, 12, 10, 9, 1 };
  
      MergeSort ob = new MergeSort();
      ob.mergeSort(arr, 0, arr.length - 1);
  
      System.out.println("Sorted array:");
      printArray(arr);
    }
}

I am completely new to java, I started it from today itself, but I do know basic of OOP's concepts. My question is Why are we creating an instance(ob) of MergeSort in void main? main method is already present inside the class MergeSort, it can directly access the function mergeSort right ? and why are we not using instantiated object of MergeSort to call printArray(arr), we are able to call printArray directly so why not mergeSort method.

Also please suggest me some sources to learn java better if you have one.

Thank you for your help.

CodePudding user response:

it can directly access the function mergeSort right ?

No, it can't, because mergeSort isn't declared as a static function, which means you need an instance of MergeSort in order to call it. That's why you're able to call printArray, because it is static, which means you don't need an instance of the enclosing class to call it.

More info on static members and methods: https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html

  • Related