Object initialization:
- Object stores non static variables.
- Non static variables automatically initializes with default values.
- We access these variables using address.
class Pro
{
int a, b;
public static void main(String[] args)
{
Pro addr = new Pro();
System.out.println("a value : " + addr.a);
System.out.println("b value : " + addr.b);
}
}
Non static variables get memory inside every object and initializes with default values automatically.
public class Pro
{
int a, b;
public static void main(String args[])
{
Pro p1 = new Pro();
Pro p2 = new Pro();
}
}
We can assign values from constructor at the time of object creation.
public class Pro
{
int a, b;
Pro()
{
this.a = 10;
this.b = 20;
}
public static void main(String args[])
{
Pro p1 = new Pro();
Pro p2 = new Pro();
System.out.println("p1 details : " + p1.a + "\t" + p1.b);
System.out.println("p2 details : " + p2.a + "\t" + p2.b);
}
}
- In the above code, all objects contain same values, but we need to initialize different objects with different set of values.
- We use arguments type constructor to pass different values to different objects.
public class Pro
{
int a, b;
Pro(int x, int y)
{
this.a = x;
this.b = y;
}
public static void main(String args[])
{
Pro p1 = new Pro(10, 20);
Pro p2 = new Pro(30, 40);
System.out.println("p1 details : " + p1.a + "\t" + p1.b);
System.out.println("p2 details : " + p2.a + "\t" + p2.b);
}
}
When we access a variable directly inside the block, first it is looking for local variable. If the local variable is not present, it is looking for static or non static variable with the same identity
public class Pro
{
int a;
Pro(int x)
{
a = x;
}
public static void main(String args[])
{
Pro obj = new Pro(10);
System.out.println("a value : " + obj.a);
}
}
public class Pro
{
int a;
Pro(int a)
{
a = a;
}
public static void main(String args[])
{
Pro obj = new Pro(10);
System.out.println("a value : " + obj.a);
}
}