While writing any piece of code in Java, there is a certain set of rules and regulations that need to be followed, that is considered as a standard. For example − A class contains variables, and functions. The functions can be used to work with the variables. Classes can be extended, and improvised too.
Basic structure
List of packages that are imported; public class <class_name> { Constructor (can be user defined or implicitly created) { Operations that the constructor should perform; } Data elements/class data members; User-defined functions/methods; public static void main (String args[]) extends exception { Instance of class created; Other operations; } }
Execution of a Java program begins from the ‘main’ function. Since it doesn’t return anything, its return type is void. It should be accessible by the code hence it is ‘public’.
Constructors are used to initialize the objects of a class that is previously defined. They can’t be declared with the keywords ‘final’, ‘abstract’ or ‘static’ or ‘synchronized’.
On the other hand, user defined functions perform specific tasks and can be used with keywords ‘final’, ‘abstract’ or ‘static’ or ‘synchronized’.
Example
public class Employee { static int beginning = 2017; int num; public Employee(int i) { num = i; beginning++; } public void display_data() { System.out.println("The static value is : " + beginning + "\n The instance value is :"+ num); } public static int square_val() { return beginning * beginning; } public static void main(String args[]) { Employee emp_1 = new Employee(2018); System.out.println("First object created "); emp_1.display_data(); int sq_val = Employee.square_val(); System.out.println("The square of the number is : "+ sq_val); } }
Output
First object created The static value is : 2018 The instance value is :2018 The square of the number is : 4072324
A class named Employee has different attributes and a constructor is defined that increments one of the attributes of the class. A function named ‘display_data’ displays the data present in the class.Another function named ‘square_val’ returns the square of a specific number. In the main function, an instance of the class is created and the functions are called. Relevant output is displayed on the console.