Static keyword java explanation

package com.zakilive.ooplearningbyme;

class Employee{
    int salary;
    int eid;
    static String ceo; //if i don't made the static it will show the last name of ceo


    static{ //it is block of static and load a class it is for same thing //it only starts when you load a class
        ceo="John";
        System.out.println("In Static");
    }

    public Employee(){  //if we use non static then we use constructor it is for different thing //it only starts when you create an object
        eid=1;
        salary=3000;
        System.out.println("In constructor");
    }

    void show(){
        System.out.println(eid+":"+salary+":"+ceo);
    }
}


public class StaticDemoExampleByMe {
    static int i=0;
    public static void main(String[] args) {
        //creating two objects where leo and cario works for same company, so they have same ceo
        Employee leo=new Employee();
        Employee cario=new Employee();


         i=0; //you will get error because i is non static variable and it is inside a static class
//        leo.salary=5000;
//        leo.eid=2;
//        Emp.ceo="Fiona";
//
//        cario.salary=4000;
//        cario.eid=3;
//        Emp.ceo="Fiona"; //for static variable we prefer class name we don't need object
//        Emp.ceo="Jen";

        leo.show();
        cario.show();

     }
}

Some of the concepts learn from this video:

 

and this blog post

https://beginnersbook.com/2013/04/java-static-class-block-methods-variables/

 

This blog site can be seen for future references:

Head First Java Chapter 10 Notes

It would be a great help, if you support by sharing :)
Author: zakilive

Leave a Reply

Your email address will not be published.