CoreJava-14 - Fillers -Static vs Non Static


 

Static vs. Non-Static in Java


What are Static and Non-Static?

  • Static: In Java, the static keyword is used to create members (variables and methods) that belong to the class rather than to any instance of the class. These members are also referred to as "class members."
  • Non-Static (Instance): Non-static members, also known as instance members, are associated with instances (objects) of the class. Each instance of a class has its own set of non-static members.

Access Modifiers:

  • Static: Static members can have any access modifier (public, private, protected, or package-private) depending on the intended visibility and usage. For example, you can have a private static variable that is only accessible within the class.
  • Non-Static: Non-static members can also have any access modifier, but their visibility depends on the object's access to them. Private non-static members are only accessible within the class, while public ones are accessible from anywhere.

Calling Static vs. Non-Static Members:

  • Static: Static members can be accessed directly using the class name. You don't need to create an instance of the class to access them. For example:
  • Non-Static: Non-static members can only be accessed through an instance of the class. You must create an object of the class to access non-static members. For example:

ClassName object = new ClassName();

object.nonStaticMethod();

object.nonStaticVariable;

Applicability:

  • Static: Static members are typically used for things that are shared among all instances of the class. Common examples include constants, utility methods, and counters that need to be shared across instances.
  • Non-Static (Instance): Non-static members are used for properties and behaviors that are unique to each instance of the class. They store and represent the state of individual objects.

Static and Non-Static Blocks:

  • Static Initialization Block: Java allows you to create static blocks within a class. These blocks are executed when the class is first loaded, typically used for static member initialization or other class-level setup.

static { // Code to initialize static members or perform other class-level setup }

  • Instance Initialization Block or Non Static Block: You can also create instance initialization blocks that are executed when an object is created, before the constructor is called. These blocks are used for common instance-level initialization tasks.

{ // Code to initialize instance members or perform other instance-level setup }

Inheritance:

  • Static: Static members are inherited in a subclass, but they cannot be overridden. They can be accessed using the subclass name if they are visible based on the access modifiers.
  • Non-Static: Non-static members are inherited in a subclass, and they can be overridden if they are methods. The subclass can provide its own implementation of an inherited method.

Polymorphism:

  • Static: Static members are not polymorphic. The method called depends on the reference type, not the actual object type.
  • Non-Static: Non-static methods can exhibit polymorphism when overridden in subclasses. The method called depends on the actual object type.

Initialization:

  • Static: Static members are initialized when the class is first loaded. They can also be initialized in a static initialization block or when they are declared.
  • Non-Static: Non-static members are initialized when an instance of the class is created. They can be initialized in an instance initialization block or when they are declared.

Memory Usage:

  • Static: Static members are stored in memory for the entire duration of the program. They are shared among all instances of the class.
  • Non-Static: Non-static members are stored in memory for each individual object (instance) created from the class. Each instance has its own set of non-static members.

Methods:

  • Static: Static methods cannot access non-static members directly because they are not associated with any specific instance. They can only access other static members.
  • Non-Static: Non-static methods can access both static and non-static members because they are associated with a specific instance.

Use Cases:

  • Static: Use static members for utility methods (e.g., Math.sqrt()), constants (e.g., Math.PI), counters shared among instances, and factory methods.
  • Non-Static: Use non-static members to represent the state of individual objects (instance variables) and define behaviors specific to instances (instance methods).

Memory Management:

  • Static: Static members are stored in a special area of memory known as the "Method Area" or "PermGen" (prior to Java 8). They are loaded when the class is first accessed and persist throughout the program's execution.
  • Non-Static: Non-static members are stored in the object's memory allocation, which is part of the heap. Each instance has its own set of non-static members, consuming memory accordingly.

Constructors:

  • Constructor: Constructors are special methods used to initialize objects of a class. They can be either static or non-static.

public ClassName() {

// Code for non-static constructor }

public static ClassName() {

// Code for static constructor (rarely used) }

    • Non-static constructors are called when you create an instance of the class using new ClassName().
    • Static constructors (if defined) are called when the class is first loaded, and they are less common in Java.

Example covering flow with Multiple Blocks and Constructors:

public class ExampleClass {

static {

// Static initialization block - runs when the class is loaded

System.out.println("Static Initialization Block"); }

 

{ // Instance initialization block - runs when an object is created

System.out.println("Instance Initialization Block"); }

 

// Non-static constructor

public ExampleClass() {

System.out.println("Non-Static Constructor"); }

 

public static void main(String[] args) {

System.out.println("Main Method");

// Creating instances to invoke instance initialization block and constructor

ExampleClass obj1 = new ExampleClass(); ExampleClass obj2 = new ExampleClass(); } }

 

 

Output:

Static Initialization

Block Main Method

Instance Initialization Block

Non-Static Constructor

Instance Initialization

Block Non-Static Constructor

 

In this example, you can see the flow of execution when there are static and instance initialization blocks along with constructors in a Java class. The static block is executed when the class is loaded, the instance block is executed when objects are created, and the constructors are called during object creation.

Example with All Aspects:

public class ExampleClass {

 private static int staticVar = 0;

private int instanceVar = 0;

 

static {

 System.out.println("Static Initialization Block");

staticVar = 10; }

 

{ System.out.println("Instance Initialization Block"); instanceVar = 20; }

 

public ExampleClass() {

System.out.println("Non-Static Constructor"); }

 

public static void staticMethod() {

System.out.println("Static Method"); }

 

public void instanceMethod() {

System.out.println("Instance Method"); }

 

public static void main(String[] args) {

System.out.println("Main Method");

ExampleClass.staticMethod();

ExampleClass obj1 = new ExampleClass();

obj1.instanceMethod();

ExampleClass obj2 = new ExampleClass();

obj2.instanceMethod(); } }

Output:

Static Initialization

Block Main Method

Static Method Instance

Initialization Block

Non-Static Constructor

Instance Method

Instance Initialization

Block Non-Static Constructor

Instance Method

 

In this comprehensive example, we cover various aspects of static vs. non-static members, including access modifiers, inheritance, polymorphism, initialization, memory usage, static methods, and use cases.

 


Comments

Popular posts from this blog

FrontEnd - FAQs - Part 1

Java Script - FAQs

CoreJava - ClassesObjectsMethods - Assignment