Java Class Methods
Usually in Java, we declare methods inside the class, and they are used to perform certain actions as we have seen before in Java Methods chapter.
Example
In the below example, we create a method print() and in the main class we called the method using the same method name followed by parentheses () and the semicolon ;
public class classMethod { static void print(){ System.out.println("Welcome to SparkDatabox"); } public static void main(String args[]){ print(); } }
Output
Welcome to SparkDatabox
Static or Public
In Java, we either use static or public attributes and methods.
In the above example, we created a static method, which means that it can be accessed without creating an object of the class unlike public, which can only be accessed by objects.
Example
The below example demonstrates between static and public methods:
public class StaticvsPublic { static void staticMethod(){ System.out.println("Static methods can be called without creating objects"); } public void publicMethod(){ System.out.println("Public methods must be called by creating objects"); } public static void main(String args[]){ staticMethod (); StaticvsPublic myObj = new StaticvsPublic(); myObj.publicMethod(); } }
Output
Static methods can be called without creating objects Public methods must be called by creating objects
Access Methods with an Object
The public methods can be accessed with an object with the dot operator (.)
Example
public class Person { public void name(String name){ System.out.println("Name : " +name); } public void designation() { System.out.println("Software Engineer"); } public static void main (String args[]){ Person emp = new Person(); emp.name("John"); emp.designation(); } }
Output
Name : John Software Engineer
Example – Explanation
Note: The dot (.) is used to access the object’s attributes and methods.
Using Multiple Classes
Usually we practice to create an object of a class and access it in another class. Remember that the name of the java class should be same as file name.
Example:
We create two files under the same directory / folder:
EmployeeDetails.java
package practices; public class EmployeeDetails { public void name(String name){ System.out.println("Employee name : "+name); } public void employee_id(int emp_id){ System.out.println("Employee id : "+emp_id); } }
EmpMain.java
package practices; public class EmpMain { public static void main(String args[]){ EmployeeDetails emp = new EmployeeDetails(); emp.name("Eric"); emp.employee_id(456); } }
Output
Compile both the files and below is the output :
Employee name : Eric Employee id : 456