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 classMyClass{ static voidstart() { 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"
classOtherClass{ voidstart() { System.out.println("Machine Starting !"); } } public classMyClass{ public static void main(String[] args) {// First create object of OtherClassOtherClassobj1= new OtherClass();// call start() method with created objectobj1.start(); } }
Output:-
Machine Starting !
In this way you can create multiple objects and call multiple methods with it.
classOtherClass{ voidstart() { System.out.println("Machine Starting !"); } voidrun() { System.out.println("Machine Running !"); } voidstop() { System.out.println("Machine Stopped !"); } } public classMyClass{ public static void main(String[] args) { System.out.println("Calling first object:"); System.out.println(" "); OtherClassobj1= new OtherClass();obj1.start();obj1.run();obj1.stop(); System.out.println(" "); System.out.println("Calling second object:"); System.out.println(" "); OtherClassobj2= 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 ! 