Instance Members in Java
All non-static members (variables , methods) are called instance members.
Instance members are encapsulated into object.
Every object has its own copy of instance members.
- Instance data fields (either variable or constants)
- Instance methods
- Non-static initializer block (instance block)
- Inner class
Non-static/Instance Variable :
-
Instance variables are declared in a class, but outside a method.
-
When a space is allocated for an object in the heap, a slot for each instance variable value is created.
-
Instance variables have default values. For numbers the default value is 0, for Booleans it is false and for object references it is null.
Example
class Demo { int x; public static void main(String []arg) { Demo ob1 = new Demo(); Demo ob2 = new Demo(); } } Here x is non-static variable of integer type in class Demo. There will be separate copy of x created for all instance of Demo class.
Non-static Method
Usually create to operate instance data of the class.
A non-static method can access other static & non-static members (variables, methods) in the same class directly.
A non-static method implicitly provides 2 references :
this : Reference to the current object.
super : Reference to the super object.
Example
class Demo { int x; static int y ; void show() { /* direct accessing of both static and non-static */ System.out.println("x :"+x); System.out.println("y :"+y); } public static void main(String []arg) { Demo ob1 = new Demo(); /*since show is non-static object is required to access in static method */ ob1.show(); } }
Non-Static Block :
-
Non-static block of code provided in the class, execute every time an object of the class is constructed.
-
It automatically executes right after the allocation of non-static data fields and just before the invocation of constructor.
-
It can be used to initialized the non-static data fields with some dynamic value.
Example
class Demo { // non-static block { System.out.println("Non-Static Block"); } public static void main(String []arg) { Demo ob1 = new Demo(); Demo ob2 = new Demo(); //Anonumous Object new Demo(); } }OUTPUT :
Non-Static Block Non-Static Block Non-Static Block
Next topic is java-naming-conventions
Training For College Campus
We offers college campus training for all streams like CS, IT, ECE, Mechanical, Civil etc. on different technologies
like
C, C++, Data Structure, Core Java, Advance Java, Struts Framework, Hibernate, Python, Android, Big-Data, Ebedded & Robotics etc.
Please mail your requirement at info@prowessapps.in
Projects For Students
Students can contact us for their projects on different technologies Core Java, Advance Java, Android etc.
Students can mail requirement at info@prowessapps.in