4. Members Of Class

4. Members Of Class

Members of Class

Fields:

  • These are the properties of the class or object which are going to create.
  • Example: if we are creating a class called car than they have property like model, color, seat, category etc.
  • In a simplified way it can said as variables, which holds values.?

Methods:?

  • (General) behavior or the action that can be performed by an object or a class (Technically).
  • A method is a set of code which is referred to by name and can be called (invoked) at any point in a program simply by utilizing the method names
  • Method can return a value, it represents the behavior of the class or object.?

  • Anything developed within the class body is known as members of the class.
  • The members are categorized into two types

  1. Static members
  2. Non-static members

  • All static members are declared using static keyword. Classname.memberName
  • The static members are referred by using (.) dot operator on the class name

  • Non-static members are declared without using static keyword.
  • The non-static members are referred by creating instance of the class.
  • Here also (.) dot operator is used to refer non-static members classname RefeferenceVariable - new constructor(); ReferenceVariable.memberName

Static members

The static keyword in java is used for memory management mainly. We can apply java static keyword with variables, methods, blocks and nested class. The static keyword belongs to the class than instance of the class.

The static can be:

  1. variable (also known as class variable)
  2. method (also known as class method)
  3. block
  4. nested class

Java static variable

If you declare any variable as static, it is known static variable.

  • The static variable can be used to refer the common property of all objects (that is not unique for each object) e.g. company name of employees, college name of students etc.
  • The static variable gets memory only once in class area at the time of class loading.

Advantage of static variable

It makes your program memory efficient (i.e. it saves memory).

Java static method

If you apply static keyword with any method, it is known as static method.

  • A static method belongs to the class rather than object of a class.
  • A static method can be invoked without the need for creating an instance of a class.
  • Static method can access static data member and can change the value of it.

Advantages

  • Allows many classes access to behaviour that isn't dependent on an instance of any of them
  • Grouping together stateless utility methods in a helper class makes it clear what's happening and creates a class that is?cohesive?(all methods doing related work) and?coherent?(consistent use of parameters and return types).
  • Might possibly give performance advantages because static methods never need a null check and are always candidates for inlining - but the Hotspot JVM is so good at these that this is only worth worrying about in extreme cases.

Disadvantages

  • Because the?class name?is specified by each caller, you can't substitute a different class during unit testing or integration testing
  • For the same reason, users of the class can never change a static method's behaviour (or add extra behaviour to it) by creating a subclass, proxy, decorator etc.
  • Nothing stops you adding state to a class with static methods, which then act like global variables with all the well-known disadvantages of side-effects etc.

I would go further than other people who've answered this question - public static methods should probably?only ever be used?on stateless classes with no public constructor. You shouldn't use them on factory classes because of the disadvantages above - especially the problem that if I want to subclass the factory, so that the factory method can produce a subclass of the object it was originally a factory for, I can't if it's a static method.

Programs:

public class DemoStatic
{
	static int i=10;
	public static void main(String[] args) 
	{
		System.out.println("Program starts...");
		System.out.println("The value of i is: "+DemoStatic.i);
		System.out.println("Program ends...");
	}
}        

Output:

Program starts...

The value of i is: 10

Program ends...

public class DemoStaticMethod 
{
	public static void test()
	{
		System.out.println("Running static test method: ");
	}
	public static void main(String[] args) 
	{
		System.out.println("Program starts...");
		DemoStaticMethod.test();
		System.out.println("Program ends...");
	}
}        

Output:

Program starts...

Running static test method:?

Program ends...

public class DemoNonStaticVariables 
{
	int i = 10;
	public static void main(String[] args) 
	{
		System.out.println("Program starts...");
		DemoNonStaticVariables d = new DemoNonStaticVariables();
		System.out.println("The value of i is : "+d.i);
		System.out.println("Program ends...");
	}
}        

Output:

Program starts...

The value of i is : 10

Program ends...

public class DemoNonStaticMethod 
{
	public void test()
	{
		System.out.println("Running non-static test() method: ");
	}
	public static void main(String[] args) 
	{
		System.out.println("program starts...");
		DemoNonStaticMethod d = new DemoNonStaticMethod();
		d.test();
		System.out.println("Program ends...");
	}
}        

Output:

program starts...

Running non-static test() method:?

Program ends...

Memory?

Computer memory is any physical device capable of storing information temporarily or permanently.

  • Memory is classified into two types

  1. Read only memory
  2. Read/write memory

Read only memory: Write once, read multiple times

Read/Write memory: it is classified into two types,

Note:? - Program is made-up of two segments

  • Data segment
  • Code segment

  • Every program which executes is consumes the RAM memory.

Programs

public class Demo 
{
	static int i = 10;
	int k = 21;
	public static void main(String[] args)
	{		
		System.out.println("Program starts...");
		System.out.println("Value of i is: "+Demo.i);
		Demo d = new Demo();
		System.out.println("Value of k is: "+d.k);
		System.out.println("Program ends...");
	}
}
        

Output:

Program starts...

Value of i is: 10

Value of k is: 21

Program ends...

Global variables And Local variables

A class can contain any of the following variable types.

On class level variables are classified into two types

  1. Global variables
  2. Local variables

Global Variables:

  • If any variables declared within a class but outside any methods are called as global variables.
  • ?It is classified into two types

  1. Static global variables

  • If any variable is declared outside the method and declared using the static keyword than those variables are called as static global variables.
  • Static global variables are referred by using class name.

  1. Non-static global variables/Instance variables

  • If any variables are declared within a class but outside any method and are declared without using any static keyword than those variables are called as non-static global variables.?
  • Instance variables are variables within a class but outside any method. These variables are instantiated when the class is loaded. Instance variables can be accessed from inside any method, constructor or blocks of that particular class.

  • A variable that is created inside the class but outside the method is known as instance variable. Instance variable doesn't get memory at compile time. It gets memory at runtime when object (instance) is created. That is why, it is known as instance variable.

Local variables:

  • Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed.

Note: -?

  1. Local variables can’t be declared as static because local variables are by default non-static.
  2. If we try to declare local variable as static we get compile time error?

‘Illegal modifier for parameter i; only final is permitted’

  1. Global variables can be declared as static and non-static.

Program:

public class Demo 
{
	static int m = 10;//Static global variable
	int n = 21; // non-static global variable
	public static void main(String[] args)
	{		
		System.out.println("Program starts...");
		int i = 10;
		System.out.println("Value of local variable i is: "+i);
		System.out.println("Value of static global variable m is: "+Demo.m);// Referring static global variable on class name
		Demo d = new Demo();
		System.out.println("Value of non-static global variable n is: "+d.n);// referring non-static global variable by using reference variable
		System.out.println("Program ends...");
	}
}        

Output:

Program starts...

Value of local variable i is: 10

Value of static global variable m is: 10

Value of non-static global variable n is: 21

Program ends...

public class Demo1 
{
	static int i = 10;
	int k = 21;
	public static void main(String[] args) 
	{
		System.out.println("Program starts...");
		System.out.println("Value of i is: "+Demo1.i);
		Demo1 d1 = new Demo1();
		System.out.println("Value of k is: "+d1.k);
		Demo1 d2 = new Demo1();
		d2.k = 40;
		System.out.println("Value of k is: "+d2.k);
		System.out.println("Program ends...");
	}
}        

Output:

Program starts...

Value of i is: 10

Value of k is: 21

Value of k is: 40

Program ends...


Note:?

  • Java memory is classified into two types

  1. Stack memory
  2. Heap Memory

  • Memory allocation

  1. Stack area is for execution (Last in first out)
  2. Heap area is for storage (Random)

Execution:

  • When we run the java program,
  • Calls the class loader -> it will load class members of java class into heap (It will load only static members)
  • JVM (Java) enters stack for execution
  • JVM calls the main method
  • JVM calls garbage collector

Programs:

public class Demo1 
{
	static int i = 10;
	static void test()
	{
		int j = 20;
		System.out.println("Value of j is: "+j);
	}
	public static void main(String[] args) 
	{
		System.out.println("Program starts...");
		Demo1.test();
		System.out.println("Program ends...");
	}
}        

Output:

Program starts...

Value of j is: 20

Program ends...

public class Demo1 
{
	static int i = 10;
	static void test()
	{
		System.out.println("Value of i is: "+Demo1.i);
	}
	static void test1()
	{
		System.out.println("Value of i is: "+Demo1.i);
	}
	public static void main(String[] args) 
	{
		System.out.println("Program starts...");
		Demo1.test();
		Demo1.i = 12;
		Demo1.test1();
		System.out.println("Program ends...");
	}
}        

Output:

Program starts...

Value of i is: 10

Value of i is: 12

Program ends...

public class Demo1 
{
	static int add(int a, int b)
	{
		System.out.println("Running Add() method: ");
		int sum = a+b;
		return sum;
	}
	public static void main(String[] args) 
	{
		System.out.println("Program starts...");
		int result = Demo1.add(12, 34);
		System.out.println("Result is: "+result);
		System.out.println("Program ends...");
	}
}        

Output:

Program starts...

Running Add() method:?

Result is: 46

Program ends...

Program to pass the value of instance to the another member

public class PassValueOfInstanceMembers 
{
	int i = 10;
	double d = 23.23;
	static void sample(int a)
	{
		System.out.println("Running sample method()");
		System.out.println("The value of a is: "+a);
	}
	public static void main(String[] args) 
	{
		System.out.println("Program starts...");
		PassValueOfInstanceMembers p = new PassValueOfInstanceMembers();
		PassValueOfInstanceMembers.sample(p.i);//First get the i value than pass to sample method
		System.out.println("Program ends...");
	}
}        

Output:

Program starts...

Running sample method()

The value of a is: 10

Program ends...

public class Demo11
{
	int i = 10;
	double d = 23.12;
	static void sample(Demo11 d)
	{
		System.out.println("Running sample method...");
		System.out.println("Value of i is: "+d.i);
		System.out.println("Value of d is: "+d.d);
	}
	public static void main(String[] args) 
	{
		System.out.println("Program starts...");
		Demo11 d1 = new Demo11();
		Demo11.sample(d1); // Passing the address of the instance
		System.out.println("Program ends...");
	}
}        

Output:

Program starts...

Running sample method...

Value of i is: 10

Value of d is: 23.12

Program ends...

Blocks

  • Blocks are like method
  • Blocks cannot be invoked
  • Static blocks will be executed before the main method
  • Static blocks are executed in a sequential order
  • Non-static blocks executed every time we create instances.

There are two types of Blocks, They are

  1. Static blocks or Static Initialization Blocks
  2. ?Non-static blocks or Instance initializer blocks?

Static initialization blocks or Static Blocks:

  • A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword. Here is an example:

static?

{

????// whatever code is needed for initialization goes here

}

  • Static initialization block is used to set values of static field if it cannot be done in one line.
  • A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code.

Ex:?

public class Demo4
{
	// Global variables
	static int i = 10;
	// Declaration and initialization
	static
	{
		i = 28;
		// Initialization
	}
	public static void main(String[] args)
	{
		System.out.println("Program starts...");
		System.out.println("Value of i is: "+Demo4.i);
		System.out.println("Program ends...");
	}	
}        

Output:

Program starts...

Value of i is: 28

Program ends...

Programs:?

public class Demo 
{
	static
	{
		System.out.println("Running 1st static block...");
	}
	public static void main(String[] args)
	{
		System.out.println("Program starts...");
		
		System.out.println("Program ends...");
	}
	static
	{
		System.out.println("Running 2nd static block...");
	}
}        

Output:

Running 1st static block...

Running 2nd static block...

Program starts...

Program ends...

Instance initializer block:

  • Instance Initializer block is used to initialize the instance data member. It run each time when object of the class is created.?

  • The initialization of the instance variable can be directly but there can be performed extra operations while initializing the instance variable in the instance initializer block.
  • What is the use of instance initializer block while we can directly assign a value in instance data member? For example:

class?Bike

{??

????int?speed=100;??

}??

  • Why use instance initializer block?

  • Suppose I have to perform some operations while assigning value to instance data member e.g. as for loop to fill a complex array or error handling etc.

class Bike
{  
    int speed;      
    Bike()
    {
    	System.out.println("speed is "+speed);
    }     
    {
    	speed=100;
    }        
    public static void main(String args[])
    {  
    	System.out.println("Program starts...");
    	Bike b1=new Bike();  
    	Bike b2=new Bike();  
    	System.out.println("Program ends...");
    }      
}        

Output:

Program starts...

speed is 100

speed is 100

Program ends...

  • There are three places in java where you can perform operations:?

  1. method
  2. constructor
  3. block

Rules for instance initializer block :

  • There are mainly three rules for the instance initializer block. They are as follows:?

  1. The instance initializer block is created when instance of the class is created.
  2. The instance initializer block is invoked after the parent class constructor is invoked (i.e. after super () constructor call).
  3. The instance initializer block comes in the order in which they appear.

public class Demo1 
{
	{
		System.out.println("Running 1st non-static block...");
	}
	public static void main(String[] args)
	{
		System.out.println("Program starts...");
		Demo1 d = new Demo1();
		System.out.println("----------------");
		Demo1 d1 = new Demo1();
		System.out.println("Program ends...");
	}
	{
		System.out.println("Running 2nd non-static block...");
	}
}        

Output:

Program starts...

Running 1st non-static block...

Running 2nd non-static block...

----------------

Running 1st non-static block...

Running 2nd non-static block...

Program ends...

public class Demo2
{
	static
	{
		System.out.println("Running static block...");
	}
	{
		System.out.println("Running non-static block...");
	}
	public static void main(String[] args)
	{
		System.out.println("Program starts...");
		Demo2 d = new Demo2();
		System.out.println("Program ends...");
	}
}        

Output:

Running static block...

Program starts...

Running non-static block...

Program ends...

public class Demo2
{
	static
	{
		System.out.println("Running static block...");
	}
	{
		System.out.println("Hi, welcome to non-static block");
	}
	public static void main(String[] args)
	{
		System.out.println("Program starts...");
		Demo2 d = new Demo2();
		System.out.println("Program ends...");
	}
	static
	{
		System.out.println("Hi, Welcome to static block");
	}
	{
		System.out.println("Running non-static block...");
	}
}        

Output:

Running static block...

Hi, Welcome to static block

Program starts...

Hi, welcome to non-static block

Running non-static block...

Program ends...

要查看或添加评论,请登录

Srinivas Prasad K T的更多文章

社区洞察

其他会员也浏览了