Menu Close

Non static members in Java

Non static members:

  • The common functionality of application becomes static.
  • Program execution starts with static members (main)
  • Static members (variables & methods) need to access using class name.
  • The specific functionality must be defined as non static.
  • These members need to access using object address.
  • Members are :
    1. non static block
    2. non static variable
    3. non static method
    4. constructor

Non static block:

  • Set of instructions without identity.
  • It is also called instance block
  • Executes every time when object creates
  • We cannot access instance block (no name)
  • JVM access implicitly every time when object creates.
class Test
{
	static
	{
		// static block
	}

	{
		// instance block
	}
}

Non static variable:

  • variables store information.
  • static variables store common information of all objects.
  • static variables data will be shared among the objects.
  • static variables get memory only once
  • instance variables store specific information of Object
  • instance variables data is unique for every object.
  • instance variables get memory when object created.

Declaration of variable inside the class and outside to blocks and methods

class Test
{
	static int a ;
	int b ;    // instance variable
	static
	{
		int c ;
	}
}

Constructor:

  • It is special java method.
  • It must be defined with class name.
  • Return type is not allowed.
  • Constructors are used to initialize instance variables in Object creation process.
class Test
{
	Test()
	{
		constructor logic...
	}
}

Non static method:

  • A block of instructions that performs a task.
  • Non static methods represent specific behavior of Object.
class Test
{
	static void common()
	{
		// static functionality
	}
	void specific()
	{
		// non static functionality
	}
}