Author Topic: Encapsulation,Inheritance and Polymorphism  (Read 1896 times)

0 Members and 1 Guest are viewing this topic.

Offline SagarDabas

  • Live Curious!!!!!!
  • Member
  • Newbie
  • *
  • Points: 1
  • Posts: 45
  • Live Curious!!!!!!
    • View Profile
Encapsulation,Inheritance and Polymorphism
« on: December 27, 2011, 11:21:23 pm »
How many of us even think before beginning a project that I should try to make my project as much Object Oriented as possible?  

Here's my small attempt to show the power of OOPs in programming..
Obviously much more can be done....

I am writing a class which can create new , read, delete or edit a file.... In file you can store anything .......

Important : Focus on the OOP not JAVA, may be you  get confused with generics but you can still learn them easily.

My first attempt
==> I thought it'd would be better to write the classes for the data (to be more cohesive) and then I'll save the different properties (instance variables) into the file separated by commas and newline characters . For example : If I want to save the groups (like moderators in this forum). I'd created a class Group with instance variables like String members [] , String description and String name.
And for reading  files, i used  split(",") method(there are many other ways in java)  to read different properties of the class Group.

I have not posted the complete code  to limit the length of the post.
public class NewsRead
{
private 
ArrayList<NewsletterletterList;
private 
ArrayList<GroupgroupList;
private 
ArrayList<SubscribersubsList;
private 
ArrayList<LoglogList;

NewsRead()
{
 
letterList=new ArrayList<Newsletter>();
 
groupList=new ArrayList<Group>();
 
subsList=new ArrayList<Subscriber>();
 
logList=new ArrayList<Log>();
 
readNewsletters(new File("Letterfile"));
 
readGroups(new File("Grfile"));

}
//########################For Creating new newsletter, log file, group or subscriber###################
public void readNewsletters(File file)
{
        try
        {
            
BufferedReader reader = new BufferedReader(new FileReader(file));
            
String line null;
            while((
line reader.readLine())!=null)
            {
                
String[] result =line.split("/");
                
int idInteger.parseInt(result[2]);
                
String[] ids=result[3].split(",");
                
int[] idsInt null
                 
int i=0;
                for(
String s:ids)
                {
                   
idsInt[i]=Integer.parseInt(s); 
                   
i++;
                }
                
Newsletter letter  = new Newsletter(result[0],result[1],id,idsInt);
                
letterList.add(letter);
            }
            
reader.close();
         }
        catch(
IOException e)
        {
            
System.out.println("Couldn't read the cardList out");
            
e.printStackTrace();
        }
}
public 
void readGroups(File file)
{
        try
        {
            
ObjectInputStream reader = new ObjectInputStream(new FileInputStream(file));
            
groupList=(ArrayList<Group>)reader.readObject();
            
reader.close();
         }
        catch(
Exception e)
        {
            
System.out.println("Couldn't read the cardList out");
            
e.printStackTrace();
        }
}
}

Problems :
1. Not Maintainable, Flexible and Reusable : I have to write separate methods for each new type of data. For example if i want to store info of Newsletter, then for that  i have to write separate  method for reading, writing, etc the Newsletter file. And the code for reading, writing is already there for Group class. So i was actually repeating the code.
2. Too much lengthy : Though that should not be a problem, but you'll see later.

Second Attempt :
==> Instead of saving each property (by delimiting them using commas and newline characters) into the file I serialized the whole object and saved it to the respective file. It saved lots of lines of code.

I haven't provided the code. Try it yourself.

Problems :
Though it reduced the size and also this code is much more maintainable but again the problem of writing the separate read,write functions for each file was still there.  The solution should be more generic  :think   .

3rd Attempt (may be 5th or 6th  :??: ) : Polymorphism was the answer......
Using Generics in Java and Interfaces I was able to reduce LOC from approx. 500 to 60. And also i just have to call the same function even for new classes (i showed this for 5 different files or classes, Groups, Newsletters,Subscribers,Log and Settings). In this code it doesn't matter how many number of classes you use for your data.
==>Remember I've only posted two methods in the previous code, there is more in that.

Problems : I'd like to see what you have to have to say on this. :think
 

public class NewsEdit
{
 public static 
ArrayList<NewsletterletterList;
 public static 
ArrayList<GroupgroupList;
 public static 
ArrayList<SubscribersubsList;
 public static 
ArrayList<LoglogList;
 public static 
ArrayList<MsettingssettingsList;

public static <
extends FileInterfacevoid readFiles(){
 
letterList=new ArrayList<Newsletter>() ;
 
groupList=new ArrayList<Group>();
 
subsList=new ArrayList<Subscriber>();
 
logList=new ArrayList<Log>();
 
settingsList = new ArrayList<Msettings>();
 
 
letterList=(ArrayList<Newsletter>)(ArrayList<T>)readFile(new File("Letterfile"));
 
groupList=(ArrayList<Group>)(ArrayList<T>)readFile(new File("Grfile"));
 
subsList=(ArrayList<Subscriber>)(ArrayList<T>)readFile(new File("Subsfile"));
 
logList=(ArrayList<Log>)(ArrayList<T>)readFile(new File("Logfile"));
 
settingsList=(ArrayList<Msettings>)(ArrayList<T>)readFile(new File("Settingsfile"));
}
public  static <
extends FileInterfaceArrayList<TreadFile(File file){
    
ArrayList<T> List = new ArrayList<T>();
        try
        {
           
ObjectInputStream reader = new ObjectInputStream(new FileInputStream(file));
            List=(
ArrayList<T>)reader.readObject();
            
reader.close();
         }
        catch(
Exception e)
        {
            
System.out.println("File : Empty");
        }
        return List;
}
public static <
extends FileInterfacevoid createNew(File file,ArrayList<Tins){
   
try
{
ObjectOutputStream writer = new ObjectOutputStream(new FileOutputStream(file));
               
writer.writeObject(ins);
     
writer.close();
}

catch(
IOException e)
{
System.out.println("Couldn't write out");           
}
}
public static <
extends FileInterfaceArrayList<Tdelete(int row,File file,ArrayList<Tins){
            
ins.remove(row);
            if(
ins.isEmpty())
            {
                
file.delete();
            }
            else
            {
                
createNew(file,ins);
            }
return(
ins);
}
}



You must me wondering where is encapsulation and inheritance......

Encapsulation : It's used in your data code (like Groups, Newsletters). I encapsulated what can change in future into separate classes. Your code which should not change like NewsEdit class should be separate from the code which can change. (There's much more in encapsulation.  :xd: )

Inheritance : Instead of interface (FileInterface here), you could've used any other simple class which would add some common functionality to your all data (it was not needed here). And then that class could be used for implementing polymorphism. The common functions in the FileInterface class was used at many other places (not shown here) to implement polymorphism.

« Last Edit: January 10, 2012, 12:19:48 am by SagarDabas »
Live Curious
You do not have permission to give points
point 0 Points

This topic did not receive points.

Offline SagarDabas

  • Live Curious!!!!!!
  • Member
  • Newbie
  • *
  • Points: 1
  • Posts: 45
  • Live Curious!!!!!!
    • View Profile
Encapsulation,Inheritance and Polymorphism
« Reply #1 on: December 28, 2011, 01:50:36 pm »
pdf attached

1. OOPS, Classes and Objects.
2. Inheritance, Polymorphism and Encapsulation.
3. IS-A and HAS-A relationship.
4. Designing OO application step by step.
« Last Edit: December 28, 2011, 02:05:45 pm by SagarDabas »
Live Curious

 

Sitemap 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49