Showing posts with label Objects. Show all posts
Showing posts with label Objects. Show all posts

Monday, June 27, 2016

Relationship Between Objects Java

Relationship Between Objects

It is possible to create objects for different classes and establish relationship between them.When the objects are related,it is possible to access and use members of one object in another object.When an object should start processing data where where another object has left.It is helpful to pass data from one object to another object in chained form.

There are three ways to relate objects in Java:


  1. Using References
  2. Using inner class concept
  3. Using inheritance
Relating Objects using References

Let us create two classes,One and Two . Suppose we want to access the members of class two in class one,we should relate their objects.we should relate their objects .for this just declare the reference variable of class two as an instance variable in class One. 

Program:


/**
 * 
 */
package com.myobjectrelation;

/**
 * @author Abhinaw.Tripathi
 *
 */

class One 
{
  int x;
  Two t;
  
  public One(Two t) 
  {
this.t=t;
x=10;
  }
  
  public void display()
  {
 System.out.println("One x= " + x);
 t.display();
 System.out.println("Two var="+t.y);
  }
  
}

class Two
{
 int y;
 public Two(int y)
 {
this.y=y;
 }
 void display()
 {
System.out.println("Two y= " +y);
 }
}

public class ObjectRelationUsingref
{
public static void main(String[] args) 
{
Two obj2=new Two(22);
One obj1=new One(obj2);
obj1.display();
}
}


Result:

One x= 10
Two y= 22
Two var=22


Another Sample Program:

/**
 * 
 */
package com.myobjectrelation;

/**
 * @author Abhinaw.Tripathi
 *
 */
class OneA
{
TwoB obj2;
public OneA(TwoB obj2)
{
  this.obj2=obj2;
}
double cube(double x)
{
double result=x*obj2.square(x);
return result;
}
}

class TwoB
{
Three obj3;
public TwoB(Three obj3) 
{
this.obj3=obj3;
}
double square(double x)
{
double result=x*obj3.get(x);
return result;
}
}

class Three
{

public double get(double x) 
{
return x;
}
 
}

public class Relate
{
public static void main(String[] args)
{
Three obj3=new Three();
TwoB obj2=new TwoB(obj3);
OneA obj1=new OneA(obj2);
double result=obj1.cube(5);
System.out.println("cube of 5 ="+result);
double result2=obj2.square(5);
System.out.println("square of 5 ="+result2);
}

}


Result:

cube of 5 =125.0
square of 5 =25.0


What is Object Graph?

Ans: Object graph is a graph showing relationship between different objects in memory.

Inner Class

Inner class is a class written within another class.Inner class is a basically a safety mechanism,since it is hidden from other classes in its outer class.

To make instance variables not available outside the class,we use private access specifier before the variables.this is how we provide the security mechanism to variables.Similarly,in some cases,we want to provide security for the entire class.in this case we use private access specifier before class.?.the problem is if we use private access specifier before a class ,the class is not available to the java compiler or JVM .So it is illegal to use private before a class name in java.

But private is allowed before an inner class and thus it is useful to provide security for the entire inner class because it is not available to other classes.This means an object to inner class can not be created in any other class.

Program:

/**
 * 
 */
package com.myobjectrelation;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author Abhinaw.Tripathi
 *
 */

class  BankAcct
{
 private double bal;
 public BankAcct(double b)
 {
this.bal=b;
 }
 void contact(double r) throws IOException
 {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Password: ");
String password=br.readLine();
if(password.equals("abhinaw"))
{
Interest in=new Interest(r);
in.calculateInterest();
}
else
{
System.out.println("Sorry,you are not an authorized person");
return;
}
 }
 private class Interest
 {
private double rate;
     public Interest(double r) 
     {
this.rate=r;
}  
     
     void calculateInterest()
     {
    double interest=bal*rate/100;
    bal+=interest;
    System.out.println("updated Balance="+bal);
     }
 }
}

public class BankAccount
{
public static void main(String[] args) throws IOException
{
BankAcct account=new BankAcct(100000);
account.contact(9.5);
}

}

Result:

Enter Password: 
abhinaw
updated Balance=109500.0


Note: 

The inner class object will contain an additional field by the name this$0 which stores the reference number of the outer class object in memory.this is this$o is invisible field because reference of outer class object is available to inner class object,now inner class is able to refer to all the members of the outer class.
  1. An inner class is a safety mechanism .
  2. Inner class is hidden from other classes in its outer classes.
  3. An object to inner class can not be created into other classes.
  4. An object to inner class can be created only in its outer class.
  5. Inner class members can access the members of the outer class directly.
  6. Inner Class and Outer Class objects are created in separate memory locations.
  7. When same names are used, we can refer to outer class members in the inner class.
  8. Inner class decrease readability of a program.This is against the design principal of Java to be a simple programming language.

Anonymous Inner Class

It is an inner class without a name and for which only a single object is created.
Anonymous inner classes are very useful in writing implementation classes for listener interfaces in graphics programming or Android interfaces.Lets understand it by a simple program.

Program:

/**
 * 
 */
package com.myobjectrelation;

import java.awt.Button;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * @author Abhinaw.Tripathi
 *
 */

class MyClass implements ActionListener
{

@Override
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
 
}

class But extends Frame
{
  public But() 
  {
Button btn=new Button();
add(btn);
btn.addActionListener(new MyClass());
  }
}

public class AnonymousListProg 
{

public static void main(String[] args)
{
But obj=new But();
obj.setSize(400,300);
obj.setVisible(true);

}

}


Result: A window will pop up and when you will click on it ,it will be gone.

  • MyClass is inner class inside But class.
  • The name MyClass is not written in its outer class i.e. But class.
  • MyClass object is created only once.
  • MyClass code is directly copied into the method parameter.

What is Anonymous Class?

Ans: It is an inner class whose name is not written in the outer class and for which only one object is created.

Another Example:

/**
 * 
 */
package com.myobjectrelation;

import java.awt.Button;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * @author Abhinaw.Tripathi
 *
 */
public class AnotherAnonyExample extends Frame
{
public AnotherAnonyExample()
{
Button b=new Button();
add(b);
b.addActionListener(new ActionListener() 
{
@Override
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});  
}
public static void main(String[] args) 
{
But obj=new But();
obj.setSize(400, 300);
obj.setVisible(true);
}
}

Result: A window will pop up and when you will click on it ,it will be gone.

Note: Finally,anonymous inner class is helpful when we want to pass entire class code to a method,where the class name is not written but an object is created to it.

Another way of relating objects is inheritance which we have already discussed.

Thursday, June 16, 2016

The Collection Frame Work BeginningJava

Using an Array to Store a Group of Objects

It is possible to store a group of objects into an array.Let us take an example,

Employee arr[]=new Employee[100];
This array can store 100 Employee objects.This can be achieved using a single loop as:

for(int i=0;i<100;i++)
{
  arr[i] =new Employee[data];
}

So,here are few points:

  • Arrays can not grow dynamically.Its size is fixed and at run time its size can not increased or decreased.
  • We can not store different class objects into the same array.The reason is that an array can store only one data type of elements.
  •  Adding the objects at the end of an array is easy but inserting and deleting in middle is difficult.
Collection Objects:

A collection object or a container is an object which can store a group of other objects.A collection object has a class called as Collection Class or Container Class .A group of collection classes are available in the package java.util  and is called Collection Framework.

In fact ,collection object does not store the physical copies of other objects.Since other objects are already available in memory,storing another copy of them into the collection object would be a wasting of Memory.So JVM does not store the copies instead it simply stores the references of other objects into a collection object.

Does a collection object store copies of other objects or their references?
Ans: A collection object stores references of other objects.

All the collection classes in java.util package are the implementation classes of different interfaces as shown:

Interface type                                                                     Implementation classes

Set<T>                                                                                    HashSet,LinkedHashSet

List<T>                                                                                   Stack,LinkedList,ArrayList,Vector

Queue<T>                                                                              LinkedList

Map<K,V>                                                                             LinkedList,HashMap,Hashtable


Sets: A set represents a group of element arranged just like an array.The set will grow dynamically when the elements  are stored into it.A set will not allow duplicate elements.

Lists: Lists are like sets.They store a group of elements.But lists allow duplicate values to be stored.

Queues: A queue represents arrangement of elements in FIFO.This means that an element that is stored as a first element into the queue will be removed first from the queue.

Maps: Maps store elements in the form of key and value pairs.If the key is provided then its corresponding value can be obtained . of curse the keys should have unique values.

Note: In all cases the elements refer to objects only.This means we can not store primitive data type in the collection.

Can you store primitive data type into a collection?
Ans is NO,collections store only objects.

Retrieving Elements  from Collections:
  • Using for-each loop
  • Using Iterator interface
  • Using ListIterator interface
  • Using Enumeration interface
What is the difference between Iterator and ListIterator?
Ans: Both are useful to retrieve elements from a collection.Iterator can retrieve the elements only in forward direction but in ListIterator can retrieve the elements in forward and backward direction also.

What is difference between Enumeration and Iterator?
Ans: Both are useful to get the elements from a collection.Iterator has methods whose names are easy to follow and Enumeration methods are difficult to remember.Also Iterator has an option to remove elements from the collection which is not available in Enumeration.




Serialization and De-Serialization of Objects

Serialization of Objects:

We write some programs where we stored only text into the files and retrieved same text from the files.These text files are useful when we do not want to perform any calculations on the data.What happens if we want to store some structured data in the files.

For Example:

class Employee implements Serializable
{
  private int id;
  private String name;
  private float salary;
  private Date date;
}

Then create an object to this class and store actual data into that object.Later on this object should be stored into a file using ObjectOutputStream.So,seralizable interface should be implemented by the class whose objects are to be stored into the file.

Serializable interface is an empty interface without any members in it.It does not contain any methods also.Such an interface is called "marking Interface or Tagging Interface".marking interface is useful to mark the objects of a class for a specified purpose.
For example, Serializable interface marks the class,for a specified  purpose. So that can be written into the file.If serializable interface is not implemented by the class then writing that class objects into a file will lead to NotSerializableException .

Note: However, any static and transient variables of the class can not be serialized.

What is De-serialization?

Ans: De-Serialization is a process of reading back the objects from a file.

Program:

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Date;

/**
 *
 */

/**
 * @author Abhinaw.Tripathi
 *
 */
class Employee implements Serializable
{
 private int id;
 private String name;
 private float sal;
 private Date obj;

 public Employee(int i,String n,float s,Date d)
 {
this.id=i;
this.name=n;
this.obj=d;
this.sal=s;
 }

 public void display()
 {
System.out.println(id + "\n");
System.out.println(name + "\n");
System.out.println(sal + "\n");
System.out.println(obj + "\n");
 }

 public static Employee getData() throws IOException
 {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter emp id:" );
int id=Integer.parseInt(br.readLine());

System.out.println("Enter emp name:" );
String name=br.readLine();

System.out.println("Enter emp Salary:" );
float sal=Float.parseFloat(br.readLine());

Date d=new Date();

Employee e=new Employee(id, name, sal, d);

return e;

 }

}

public class SerializableStoreObjectApp
{

public static void main(String[] args) throws Exception
{
 BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
 FileOutputStream  fos=new FileOutputStream("objFile");
 ObjectOutputStream ois=new ObjectOutputStream(fos);

 System.out.println("How many objects?.");
 int n=Integer.parseInt(br.readLine());

 for(int i=0;i<n;i++)
 {
 Employee e1=Employee.getData();
 ois.writeObject(e1);  
 }
 ois.close();
}

}

Output:
How many objects?.
2
Enter emp id:
1
Enter emp name:
abhinaw
Enter emp Salary:
1000
Enter emp id:
2
Enter emp name:
sandeep
Enter emp Salary:
5000

Writing program to de-serialize this object:

Program:

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;

/**
 * 
 */

/**
 * @author Abhinaw.Tripathi
 *
 */
public class GetObjectDeserialize
{

public static void main(String[] args) 
{
ObjectInputStream ois = null;
try
{
FileInputStream fis=new FileInputStream("objFile");
ois=new ObjectInputStream(fis);
Employee e;
while((e=(Employee)ois.readObject())!=null)
{
e.display();
}
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
try {
ois.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

}

Output:

1

abhinaw

1000.0

Thu Jun 16 17:33:06 IST 2016

2

sandeep

5000.0

Thu Jun 16 17:33:18 IST 2016