All about static snippet (Java)
April 27, 2016
Categorised in: Java Codes
import java.util.Random; public class Emp { //To get a unique employee id i.e. it doesn't starts with 0 static private int empId; private int actualEmpid; private String empName; private int empSal; static private String compName; static private int totalEmp = 0; //Java has 3 things: Static data, static function and static block static{ //This is executed just after creation of object. After object creation, static datas are created n then static block. System.out.println("Static block created..."); Random random = new Random(); //Random number in the range 0-1000 empId = random.nextInt( 1000 ); } Emp(){ //Constructor //Post increment so that it is assigned first and then incremented this.actualEmpid = empId++; Emp.totalEmp++; } public String getEmpName() { return empName; } public void setEmpName(String empName) { this.empName = empName; } public int getEmpSal() { return empSal; } public void setEmpSal(int empSal) { this.empSal = empSal; } public static String getCompName() { return compName; } public static void setCompName(String compName) { Emp.compName = compName; } public static int getTotalEmp() { return totalEmp; } public static void setTotalEmp(int totalEmp) { Emp.totalEmp = totalEmp; } public void display(){ System.out.println("Emp. ID : " + this.actualEmpid + " Name: " + empName + " Emp. Salary: " + empSal + " Company Name: " + Emp.compName); } public static void main(String [] args){ //because of static we can do this before creation of any object. Emp.setCompName("Rambo"); Emp e1 = new Emp(); e1.setEmpName("Pratik"); e1.setEmpSal(5000); Emp e2 = new Emp(); e2.setEmpName("Rohit"); e2.setEmpSal(6000); e1.display(); e2.display(); System.out.println("The total number of employees registered are: " + Emp.getTotalEmp()); } }
Output:
Static block created…
Emp. ID : 905 Name: Pratik Emp. Salary: 5000 Company Name: Rambo
Emp. ID : 906 Name: Rohit Emp. Salary: 6000 Company Name: Rambo
The total number of employees registered are: 2
Pratik Kataria is currently learning Springboot and Hibernate.
Technologies known and worked on: C/C++, Java, Python, JavaScript, HTML, CSS, WordPress, Angular, Ionic, MongoDB, SQL and Android.
Softwares known and worked on: Adobe Photoshop, Adobe Illustrator and Adobe After Effects.