Packages , static keyword , Inner Classes & Singleton Class

Photo by RetroSupply on Unsplash

Packages , static keyword , Inner Classes & Singleton Class

Packages

Packages are like folders for classes in Java. They help keep classes organized and prevent naming conflicts by allowing classes with the same name to exist in different packages.

Code snippet 1 : class greetingUser inside package1

package package1;

public class greetingUser {
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

Code snippet 2 : class greetingUser inside package2

package package2;

public class greetingUser {
    public static void main(String[] args) {
        System.out.println("Yeah!");
    }
}

The same class name greetingUser is differentiated through packages.

A convention to label packages: Write the domain name in reverse order.

Example: facebook.com

package com.facebook;


Import keyword
The "import" keyword in Java lets you use classes, methods, or variables from other packages. This helps improve code readability and saves time by avoiding duplicating code. Import specifies the full path to the reference that the current file is using.

Code snippet 3 : Import only a particular method, mention its name [greetingUser]

import package1.greetingUser;

Code snippet 4 : Imports every class from a package use *

import package1.*;

Note:

Any private classes/methods/variables cannot be imported into a different class!

static keyword: static indicates independent of an object.

public static void main(String[] args) {
        System.out.println("Yeah!");
    }

The "public static void main" (abbreviated as "psvm") is the most commonly used static method in Java. It's interesting to note that even though the "psvm" method is inside a class, it can be run without creating an object of that class. This is because the "psvm" method is static, meaning it can be accessed without an object and runs independently.

In Java, objects are created during runtime, but anything marked as static is determined at compile time.

Note:

variables/methods/classes any of them can be declared as static.

static variables

//declaring static variables
static int variable2;
//declaring & assigning static variables
static int variable1 = 10;

static blocks : initializes static variables in a non-static context

static {
        variable2 = 25;
    }

static blocks are executed only once during the compile time to assign values

Code snippet 5 : static variables and static blocks

public class staticInitialization {
    static int variable1 = 10;
    static int variable2;
    static {
        variable2 = 25;
    }
    public static void main(String[] args) {
        System.out.println("Static Variable : " + variable2); // 22
        variable2 = 28;
        System.out.println("Static Variable : " + variable2); // 28
    }
    static{
        variable2 = 22;
    }
}

class staticInitialization is a non-static class, hence a static block is necessary to initialize static variables. On the other side, psvm is a static method and so, allows static variables to be initialized without any explicit static block!
As anything static is object independent, so it runs first.

The result of the first print statement in psvm is 22 instead of 25 { all static methods/blocks are executed first, so before running the psvm method both static blocks are executed and variable2 is modified from 25 to 22. Thus 2nd static block is executed after the first static block}

And the result of the second print statement in psvm is 28 due to shadowing { selecting the closest scope variables} of the psvm scope over the class scope.

Code snippet 6 : declaring a static variable name in a class Test and initializing it in a constructor

class Test{
    static String name;
     Test(String name) {
        Test.name = name;
    }
}

Code snippet 7 : creating 2 new instances of the Test class and passing different values to both

public class StaticVariablesInClasses {
    public static void main(String[] args) {
        Test testObject = new Test("Value1");
        Test anotherTestObject = new Test("Value2");
        System.out.println(testObject.name); //Value2
        System.out.println(anotherTestObject.name); //Value2
    }
}

A static variable in a class has the same value for every instance of that class. This means that there is only one copy of that variable, which is shared among all instances. When the value of a static variable is changed, all instances will access the same updated value.

Code snippet 8 : accessing non-static methods from static methods

public class staticVsnonStatic {
    public static void main(String[] args) {

    }
    static void hello(){
        staticVsnonStatic obj = new staticVsnonStatic();
        obj.greet();
    }
    void greet(){
        System.out.println("hi");
        hello();
    }
}

Non-static methods cannot be run in a static context, but static methods can be run in a non-static context. For example, the "greet()" method is non-static, so it cannot be run from the static "psvm" method or the static "hello()" method. However, since both "psvm" and "hello()" are static, "hello()" can be run from within "psvm".

non-static greet() can be made accessible from static hello() by creating an object inside the static scope. As hello() is independent of an object while greet() requires one, it can be created in its scope itself.

Anything that is non-static in Java requires an object to be accessed. On the other hand, static methods cannot reference the "this" or "super" keywords, because "this" refers to the object's reference variable, but static methods are independent of objects.

Code snippet 9 : inner classes or nested classes

public class OuterClasses {
    static class nestedInnerClass{
    }
    public static void main(String[] args) {
        nestedInnerClass obj = new nestedInnerClass();
    }
}

outside classes cannot be static as they don't have any dependency. Inner classes cannot be accessed directly by creating an object, as they are dependent on the outer class making them non-static. Declaring the inner class as static allows it to be object independent.

Code snippet 10 : singleton class

public class Singleton {
    private Singleton() {
        // constructor
    }
    private static Singleton instance;
    public static Singleton getInstance(){
//        this method will always return the same instance
//        chk if 1 object is already created
        if (instance == null){
//         create object by calling constructor
            instance = new Singleton();
        }
        return instance;
    }
}

When only one object is to be instantiated from a class it is termed a Singleton Class. A private, object independent and singleton class-type variable is created.
private -> should not be accessible from any other outside class. static -> only 1 variable to be created to store the instance.
Purpose of singleton class -> create only 1 object & every time a new instance is trying to be created, return this same object.


Youtube link

Thanks Kunal !