Methods : Accessing from outer Classes (Part 3)

 In the last tutorials , we learned about accessing methods within the class using static keyword. Now we will learn how to access methods from outside the class i.e other classes.



Accessing methods outside the Class

Till now we used to declare methods and call them in the same class , that is why we used static keyword . static means method of main class.

eg:-
 public class MyClass {  
      static void start() {  
           System.out.println("Machine Starting !");  
      }  
      public static void main(String args[]) {  
           start();  
      }  
 }  //Outputs Machine Starting !
Here we declared and called a method in the class MyClass .


For accessing methods from outer class , we should first create objects of it and then access them.If you are not through with creating objects , visit  Objects page.

Here ( . ) keyword is used to access methods or variables of a class i.e" object . method/variable"

 class OtherClass {  
      void start() {  
           System.out.println("Machine Starting !");  
      }  
 }  
 public class MyClass {  
      public static void main(String[] args) {  
           // First create object of OtherClass  
           OtherClass obj1 = new OtherClass();  
           // call start() method with created object  
           obj1.start();  
      }  
 }  

Output:-

 Machine Starting !  


In this way you can create multiple objects and call multiple methods with it.

 class OtherClass {  
      void start() {  
           System.out.println("Machine Starting !");  
      }  
   
      void run() {  
           System.out.println("Machine Running !");  
      }  
   
      void stop() {  
           System.out.println("Machine Stopped !");  
      }  
 }  
   
 public class MyClass {  
      public static void main(String[] args) {  
           System.out.println("Calling first object: ");  
           System.out.println(" ");  
           OtherClass obj1 = new OtherClass();  
           obj1.start();  
           obj1.run();  
           obj1.stop();  
   
           System.out.println(" ");  
           System.out.println("Calling second object: ");  
           System.out.println(" ");  
           OtherClass obj2 = new OtherClass();  
           obj2.start();  
           obj2.run();  
           obj2.stop();  
      }  
 }  

Output:-

 Calling first object:   
    
 Machine Starting !  
 Machine Running !  
 Machine Stopped !  
    
 Calling second object:   
    
 Machine Starting !  
 Machine Running !  
 Machine Stopped !  


< Previous Next >