2.2 Object/Instance of class.

Object / Instance of class.

class Demo
{
int k =10;
double j = 46;
void test()
{
-
}
}

eg :
Demo ref1;
ref1 = new Demo();

Demo = ref2
ref2 = new Demo();

ref1.k = 25;
ref1.j = 48;

System.out.println(ref2.k); //10
System.out.println(ref2.j); //46

ref1
k =  25
j =  48

ref2
 10
 46

Example Program :

class  Demo5
{
int k = 10;
double j = 4.5;
void test()
{
System.out.println("running test()............!");
}
}
class MainClass
{
public static vaid main(String args[])
{
System.out.println("program started");
Demo5 ref1;
ref1 = new Demo5();
Demo5 ref2;
ref2 = new Demo5(); //ref2 = ref1 copy value of ref1 to ref2.
System.out.println("ref1 value :"+ref1);
System.out.println("ref2 value :"+ref2);

ref1.k = 25;
ref1.j = 9.8;
System.out.println(ref2.k);
System.out.println(ref2.j);
System.out.println("Program Ended");
}
}


Reference Variable :

1. When ever we create an instance of a class a copy of the class will be created in a memory. if we want to refer  a particular copy then we should used reference variable.

2. The reference variable are the special variable which is used to hold or store the object location.

3. The reference variable should be declare by class name. We can assign either null or an instance of the class.

4. We can create any number of instance for a class and each instance can be refer by different  reference variable.

5. Changes must modification made in one instance will never reflect in other instance.

6. An instance can be printed by multiple reference variable . The modification done through one reference variable will reflect in all other reference variable.

7. The static number of a class is loaded only one time in the memory (single call.) are loaded into the memory for each instance creation of the class (multiple class).

8. Static Members: are associated with the class hence its also known as class members.

9. The non-static members are associated with instance of the class hence its also known as instance members.

Note: Base of creating objects

Two ways of a creating object of a class:
1. By using new operator.
2. By using clone concept.

1. The new operator always create an object by taking the defination from class.
2. Where as the clone create the object from already create object.






Comments

Popular Posts