detect your swipe on our own

April 29, 2013 2 comments

Howdy everyone,

This has been a long long time since i wrote any post regarding anything.I have been super busy with my life and job.
But it was worth it in the end i think. Started a new job[not new now] at Progmaatic Developer Network which is a great place to work so far. Also consulting at ICDDR,B as an Android Developer in my weekend to finalize one of the project i did for them more then a year ago.

Got interested in Game Development and iOS Development.
Currently doing 1 iOS project and 1 unity3d based game.

So what will be today’s post is going to be about?

Today’s post is going to be about something that i solve pretty recently for my unit3d based game[still on going].
So, let’s get cracking 🙂 .

The game i am currently working is a 2d game.
For the gameplay i needed to know which way user was swiping, based on that direction my player will move in that direction. Since i am no longer in android or iOS where i can just use the gesture detector classes and get it done so i needed a different way. So how am i going to solve that?

Thanks to
Fletcher Dunn and Ian Parberry for their amazing book: “3D Math Primer For Graphics And Game Development”. Out of my own interest i just wanted to read this book to have some knowledge about 3d game development in general so i can have some knowledge about what’s going on underneath. There i got introduced again with some of the techniques about vector mathematics that i long forgot.

So to solve the problem i was having i applied the vector mathematics 🙂 .

To know the direction of swiping i need to know at least two position and i know can get them via touch/mouse api from unity3d.

  Vector2 m_v2DownPos = Input.touches [0].position;
  // api call to give first position 
  // user touched/mouse down and make it a Vector2
  Vector2 m_v2UpPos = Input.touches [Input.touches.Length - 1].position;
  // api call to give the last position 
  // user touched/mouse down and make it a Vector2;
  Vector2 v2delta = m_v2UpPos - m_v2DownPos; // difference between them
      if (v2delta.normalized.x >= 0.8f) {
        // user swiping in right direction
      } else if (v2delta.normalized.x <= -0.8f) {
        // user swiping in left direction
      } else if (v2delta.normalized.y <= -0.8) {
        // user swiping in down direction
      } else if (v2delta.normalized.y >= 0.8) {
        // user swiping in up direction
      }

I think you’ve got the idea of how it’s working. After getting v2delta if we normalize it, we will get the unit vector of v2delta and when you get that just check x and y component of the normalized vector to check swiping status of the user.I have defined the threshold of 0.8 . But it’s really up to you how you want to define the threshold. 1 means perfect swipe. But user hands might not be steady all the time so he/she might slip-away a little bit from perfect swipe.
Well this portion of code is applicable anywhere where we might need to calculate swipe event of our own.

So that’s it for today , until next time

“HAVE A GOOD PROGRAMMING” 🙂

FYI: This post can also be found in Progmaatic’s Blog .

Singleton pattern in android database and in general

June 24, 2012 3 comments

Howdy everyone,
It’s been a long time since i wrote any post.I have been super busy with my projects , i couldn’t manage my time to write any post for my blog.
Today i am going talk a little bit about using singleton pattern.And show you an example of it during the explanation.
Now what is it? and why do you care about it?
First let’s imagine the normal way of doing things if you are novice anough :).
Say my application consist of N number of screen.Now all screens uses an object for accessing some kind of data.If i were novice what i would do is create object of that class in every screen to access those data.
That would create N number of object.
Now since we only need to access some data but not to modify any data of that class object do we really need to create object for that class in every screen.
Of course we do if there is no pattern like singleton 🙂
Now let’s get down to what is it?As i said it’s pattern but more likely a design pattern.
Since we only need to access some data from a class, what this let’s us do is to create one object for the enitre application life cycle.And we can access those data over and over again using only single instance if that class object.
And that is what singleton mean 🙂
Why do u care? Well, i think it’s obvious, isn’t it? Save memory, Reduce complexity of the application….
Let’s see an example,
If you pay attention to class A structure you can see you can’t create any new object by
A object = new A();
Since the contructor is private the only way to get an instance of that class is calling static method getInstance of class A, so now whenever you call A.getInstance() it will return either a new object or an object that already been instantiated.

// Singleton class
    class A{
     public int a = 10;
     private static A a = null;
     private A(){
          a = this;
      }
      public static A getInstance (){
          if ( a == null )
           {
              a = new A ();
            }
        return a;
      }
    }
    // Use of singleton class
   class B{
    int myInt;
      public B(){
         System.out.println(A.getInstance().a+"");
     }
    }

Now let’s see a real exmple that might be helpful to some guys.I made this somedays ago during one of my project and documented it along the way so people who see the code can get a little bit of undertanding, what this class do?

Sqlite database for android in singlton:

package com.project;
/*
@author : Saiful Islam
@mail : saiful103a@gmail.com
*/
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DatabaseHelper extends SQLiteOpenHelper {

     // db name for this application

     private static final String DATABASE_NAME = "appdb";

     // version number of this db

     private static final int DATABASE_VERSION = 1;

     // private variable which is going to store the singlton object of this class and return it to caller

     private static DatabaseHelper dbHelper = null;
     // private SQLiteDatabase varaible which is going to be responsible for all our db related operation // no need      touch it

     private static SQLiteDatabase db = null;
   
     // a private contructor which is going to be called from getInstance method of this constructor
     
     private DatabaseHelper(Context context) {
         super(context, DATABASE_NAME, null, DATABASE_VERSION);
         // storing the object of this class to dbHelper
         dbHelper = this;
     }
   
     // Method is called during creation of the database
     /* ***************************
     *
     * BE SURE TO ENTER THE CORRECT CREATE STATEMENT FOR TABLE IN DBTable.java FOR YOUR APPLICATION NEED
     *
     */

     @Override
     public void onCreate(SQLiteDatabase database) {
      DBTable.onCreate(database);
     }
  
     // Method is called during an upgrade of the database,
     // e.g. if you increase the database version

      @Override
      public void onUpgrade(SQLiteDatabase database, int oldVersion,
     int newVersion) {
       DBTable.onUpgrade(database, oldVersion, newVersion);
      }

     // method which is going to be responsible for all our select query
     /* use case:
     * String selectSql = "Select * from table_name";
     * //be careful using try catch:
     * Cursor myCursor = null;
     * try{
     * myCursor = DatabaseHelper.getInstance.executeQuery(selectSql);
     * // ..... get the data using cursor from the db
     * }catch(Exception e){
     * e.printStackTrace(); // be sure to check if any exception is thrown and find out what is the reason
     * }finally{ // be sure to close the cursor or else, might get some unexpected behavior
     * // see if cursor really got something when requesting for something and is not closed already, just for    precaution    :)
     * if(myCursor!=null && !myCursor.isClosed){
     * myCursor.close();
     * }
     * }
     */

   public Cursor executeQuery(String sql){
    Cursor mCursor =db.rawQuery(sql, null);
     return mCursor;
   }
     // method which is going to be responsible for all insert, update and delete query
     /* use case:
     * String dmlQuery = "Insert into table_name values(....";
     * DatabaseHelper.getInstance.executeDMLQuery(dmlQuery);// will return true or false based on the action succeeded    or   not if checked?
     */

    public boolean executeDMLQuery(String sql){
    try {
      db.execSQL(sql);
       return true;
     } catch (Exception e) {
     // TODO: handle exception
      return false; 
    }
   }

     // will return a singleton object of this class will as well open the connection for convinient

    public static DatabaseHelper getInstance(Context context){
        if(dbHelper==null){
          dbHelper = new DatabaseHelper(context);
           openConnecion();
          }
         return dbHelper;
      }
     // will be called only once when singleton is created
 
    private static void openConnecion(){
          if ( db == null ){
                db = dbHelper.getWritableDatabase();
            }
      }
    // be sure to call this method by: DatabaseHelper.getInstance.closeConnecion() when application is closed by    somemeans most likely
    // onDestroy method of application

     public synchronized void closeConnecion() {
          if(dbHelper!=null){
              dbHelper.close();
                 db.close(); 
                dbHelper = null;
                db = null;
            }
        }
     }
   


package com.project;
/*
@author : Saiful Islam
@mail : saiful103a@gmail.com
*/
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class DBTable {
   // Database creation SQL statement
   // Modify this class based on the need of the app's database

      private static final String CREATE_ANTLER_TABLE = "create table if not exists mytable "
          + "(_id INTEGER PRIMARY KEY autoincrement,"
          + "name VARCHAR(20),"
          +"value VARCHAR(30));";
   
      public static void onCreate(SQLiteDatabase database) {
          database.execSQL(CREATE_ANTLER_TABLE);
      }
   
      public static void onUpgrade(SQLiteDatabase database, int oldVersion,
   int newVersion) {
         Log.w(DBTable.class.getName(), "Upgrading database from version "
           + oldVersion + " to " + newVersion
           + ", which will destroy all old data");
           database.execSQL("DROP TABLE IF EXISTS todo");
           onCreate(database);
         }
    }

I hope this help some people as it helped me.
And “HAVE A GOOD PROGRAMMING”

Categories: Android

playing with sdcard in android

September 13, 2011 Leave a comment

Howdy everyone, today i am going to share a little code snippet that i developed recently while i was playing with my usual android development journey.

I wanted to build an android file manager,where one can browse all the files from sdcard.To bring up the pace in me at first i wanted to see all the files in sdcard.And this post is about that code snippet.

Another thing i want to ask that did you familiarize yourself with ddms? If not, that’s bad bcz i am sure of that if something goes wrong in your application you probably thinking your brains out.I tell you, ddms is big big helper when the whole world is beyond your hand. 🙂

In this post i am going to use ddms too, to help me out what’s going wrong.

So, let’s not talk too much…

        File file[] = Environment.getExternalStorageDirectory().listFiles();
		FilesInDir(file);

Above line is the most mandatory one but not everythig even if it seems.

    public void FilesInDir(File[] file1){
        int i = 0;
        String filePath="";
            while(i!=file1.length){
                filePath = file1[i].getAbsolutePath();
                i++;
                Log.d(i+"", filePath);
            }
        }



Running that code snippet will show us all the files and directory name in ddms right after /mnt/sdcard/
But that’s not what i want.I want to see all the files.And that’s when i got a brilliant idea of recursion, hah maybe that’s why they teach us recursion, DnC and all.To see the world 🙂

So, let’s use it … 🙂

    File file[] = Environment.getExternalStorageDirectory().listFiles();
	recursiveFileFind(file);

    public void recursiveFileFind(File[] file1){
    int i = 0;
    String filePath="";
        while(i!=file1.length){
            filePath = file1[i].getAbsolutePath();
        	if(file1[i].isDirectory()){
        		File file[] = file1[i].listFiles();
                recursiveFileFind(file);
        	}
            i++;
            Log.d(i+"", filePath);
        }
    }

After running this we will see a "Force Close" in our emulator.

Now, what to do?Swithing to ddms perspective view we will see lots of red light:

but never fear this is where our solution is reside.

Let’s examine what is the problem:

you can see it’s a NullPointerException which is causing the problem, that means we are assigning a null reference somewhere in our code.

Closely look at the recursion:

what happens when there is only a directory left at the end of a folder but no files in it.

So that means, at that time we are assigning what’s in this below line? Which has no length!!!

		File file[] = file1[i].listFiles();

So, to fix it all we need to do is check to see if the reference is null?

	if(file1!=null){
		while(...){
		....
		}
	}

that should do it.

See how ddms helped to us to make a way when we can’t figure out things all by ourself.

That’s it for today, next i will try to write about Sensor bcz i recently added the Samsung Sensor Simulator in my eclipse, which is awesome.

Categories: Android

“TextSpeak” android app using text to speech api

August 20, 2011 25 comments

Today i’ve just developed another app for android using android’s own text to speech api.
Unlike the previous post i am going to share the apk file of this app and
i will provide the source code on request.
It’s  a pretty simple app with a neat interface.
here is a snap of this app

TextSpeak app for android

I am sure you can guess what this application does.
Of course this application only support those languages that android platform supports.

These languages are
-English
-French
-German
-Italian
-Spanish

You can see in the snapshot that there is two buttons for English, one of them
is for the guys who wants to go to America and other is for England. 🙂
And i also want to thank James of http://www.jameselsey.co.uk/blogs/techblog/
blog bcz this application is inspired from his androidsam app idea.

Download the app:   TextSpeak
Download source code:  please contact me.

Categories: Android

mediaviewer android app

August 19, 2011 Leave a comment

Hello everyone.Today i am going to share my first android app that i built recently.
I call it MediaViewer.
The app is very simple.All it does is seek to see if you have any audio,video or photo in your phone, and represent them nicely in three gallery.One for images,one audios and other is for videos.
Here are some of the screen shot that i have taken.

mainscreenphoto

You can click on any item and it will pop up another float screen with that item.
Also you can go to next item by clicking on top of the float screen.But not for video of course. 🙂
Oh, there is small button at the end of the screen if you want to contact me.
This application will be under development even though I’ve shown to you.
There are tons of idea pouring into my head and i will try to implement them, so in a way you can say that this app is the 1.0 version of MediaViewer.I will not publish it’s source code now since it has lot of things to update.When the update is done i will provide the source  code.Till then if you want to test the app for yourself please contact me.

If you have any query about anything please do comment.I’d be delighted to know.

Download app:        contact me

Categories: Android

starting with android gps

June 8, 2011 1 comment

Hello everyone, it’s been a while since my last post.It’s bcz i’ve been too lazy last few weeks figuring out what to do or what not.Though it’s not bcz of me it’s bcz my last semester exam is nearby and i have so much to do and so much to learn,Do you know the feeling when you are too excited to do lot more than you are thinking and you can not do anything at all, well i am in that situation right now.Let’s hope nothing goes wrong.
So, today i am going talk about android gps.

I am not going to dig into the theory behind android gps,rather i will try to show how you can begin development with android gps.

At first download this simple project so that you can understand what am i mockering.
WhereAmI

Open the projects code, at first, let’s see what happening in onCreate method


LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)getSystemService(context);

There may be different types of location services available in your device, to access those service we need a manager LocationManager. In this portion of the code We are getting the handle of LOCATION_SERVICE to manager, that is LocationManager.


String provider = LocationManager.GPS_PROVIDER;
Location location =
locationManager.getLastKnownLocation(provider);

Now that, we have the handler, we try to see current location by GPS service of that device,(you can also access other services using other providers (only if that’s available on your device)). Since we have the GPS_PROVIDER, now all we have to do is calling some method to see what gps is providing for us.Here we are trying to get the last known location.


locationManager.requestLocationUpdates(provider, 2000, 10,
locationListener);

This portion of the project is most important for us since it is responsible for listening the changes made by the device’s gps.
As you can see LocationManager has a method called requestLocationUpdates(java.lang.String provider, long minTime, float
minDistance, android.location.LocationListener listener) which takes as you can guess, 4 parameter.which provider to use,minimum time before listening for changes, minimum change in distance , and the listener.

Let’s see how is that listener is implemented:


private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}

public void onProviderDisabled(String provider){
updateWithNewLocation(null);
}

public void onProviderEnabled(String provider){ }
public void onStatusChanged(String provider, int status,
Bundle extras){ }
};

here we have 4 methods but what we need for this project is onLocationChanged(Location location) and onProviderDisabled(String provider).
Every-time device changes it’s location, listener will fire the onLocationChanged(Location location) method with providing the location.
now remain only is updateWithNewLocation(location) which tells our UI to update with the location.

myLocationText.setText("Your Current Position is:\n" +
latLongString);

Before you run this project you should do a simple modification in your manifest file.

add <uses-permission android:name=”android.permission.ACCESS_FINE_LOCATION”/> in your manifest. Use android.permission.ACCESS_COARSE_LOCATION if you are going to use LocationManager.NETWORK_PROVIDER.

And that’s it,wait, don’t run it right-away, we have a little housework to do.Now the Q is how the heck emulator is going to fetch the location, well that’s when mock gps comes in. It will mock you with gps location 🙂 , well not you, i mean emulator.

Fire up your emulator, after loading the emulator open your eclipse ide and go to ddms perspective view, you can see lot’s of thing happening in here. Find the emulator control.
now, i have provided a kml file with this project which stores some places location with their latitude and longitude.from emulator control’s kml “load KML” and locate the kml file.
Now run the project, after being initiated it will not show you anything bcz gps is not reading anything till now.Run the kml file from emulator control and voila, you are up and running.Isn’t it cool, you are moving from one place another without
being moved for an inch from your computer.I think that’s awesome.:)

Thanks everybody, next i will try to post something about android ndk(takes whole lot of pain only for configuring!!!) or
maybe else till then “HAVE A GOOD PROGRAMMING”

Categories: Android

android startActivity and startActivityForResult

March 19, 2011 27 comments

In my previous tutorial I have talked a little bit about intent. So we have our intention to do something either explicitly or implicitly now it’s time to start those intent. And we do this via startActivity() or startActivityForResult() but why do we have two kind of method for this.

As name suggest startAcitvity will only take you there where you wanna go without worrying about getting any result from child activity to parent activity.
It’s real classic when you have a sequence activity to go through, like filling some information in every activity and that’s it.
What if you want an activity that uses information from other activity or may be other application. In that case you need more than just startActivity(). And that’s when comes startAcitvityForResult().
So it start another activity from your activity and it expect to get some data from child activity and return that to parent activity.
Let’s see some example:

final Bundle bundle = new Bundle();
al.add(1,un.getText().toString());
bundle.putStringArrayList("Q1", al);
Intent intent=new Intent(PageOne.this,PageTwo.class);
intent.putExtras(bundle);
startActivity(intent);

In this case I just wanna go from page one to page two and I don’t expect to get something from page two but I want page two to receive some data from page one and that I have sent using intent.putExtras().Full Code: ReportGenerator

Now we will try to understand startAcitvityForResult(). using previous ContactPicker example.
If you have not downloaded it yet you can download it from:
ContactPicker
At first we should be creating an intent in our main activity that is ContentPickerTester and also create a static integer variable
public static final int PICK_CONTACT=1;
now that need to be done bcz you don’t actually know which sub activity is going to give you the result(if you are using implicit intent) so we need to somehow differentiate between sub activities so that we can take different type of action for different type of result.
Intent intent=new Intent(Intent.ACTION_PICK,
Uri.parse("content://contacts/"));

startActivityForResult() accept two parameters as it’s arguments, one is going to be the explicit or implicit intent and another is called request code which is our static variable.
startActivityForResult(intent,PICK_CONTACT);
now whenever subactivity finishes, it will return the request code you have sent, along with the data and a result code to your main activity.

Let’s look at the subactivity (ContactPicker)
In the subactivity side subactivity will finish itself and return the data to the parent whenever it gets the chance to execute the below code.
Uri outUri=Uri.parse(data.toString()+rowId);
Intent outData=new Intent();
outData.setData(outUri);
setResult(Activity.RESULT_OK,outData);
finish();

Here Activity.RESULT_OK is the result code we were talking about. Now if something goes wrong with subactivity Activity.RESULT_CANCEL will return.

I don’t know if you have noticed or not that we are not calling ContactPicker anywhere in our main activity. Well we actually calling it implicitly. See at manifest file
That in our ContactPicker activity we have something like this:

<intent-filter>

<action android:name="android.intent.action.PICK"/>

<category android:name="android.intent.category.DEFAULT"/>

<data android:scheme="content" android:path="contacts"></data>

</intent-filter>

You should also remember that when we have created an intent in our main activity we defined our action as Intent.ACTION_PICK. And of course ContactPicker has an action named android.intent.action.PICK. And also the kind of data we are looking. Android will use something called Intent Resolution to find a best fit activity and that is in our case is ContactPicker activity.So voila, startActivityForResult() will open up ur subactivity.
After choosing a contact it will return to the main activity by setting the result setResult(Activity.RESULT_OK,outData) and finishing off the subactivity.

Now all you have to do is taking care of the returned data in the main activity and that is done by
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode){
case(PICK_CONTACT):{
if(resultCode==Activity.RESULT_OK)
{
//blah blah…
}
break;
}
}
}

And that’s it. A real simple application. Awesome, isn’t it? And plz do comment or question , that will encourage me to write more. Also if there is any mistake let me know so that I can correct myself. And “HAVE A GOOD PROGRAMMING”

Categories: Android

android intent tutorial

March 14, 2011 2 comments

Today i am going to talk about something called intent. To get more in depth knowledge about android you should have basic understanding about intent.

Intent comes with your intention. It’s pretty interesting after you really understand what this is for.

Android uses two kinds of intent:

  1. Implicit Intent
  2. Explicit Intent

Let’s see a real world example, say you want some information about intent but you don’t know where to get it but you only know you want to see information about intent. So what do you do? You will be open up your browser -> go to google -> and enter something about intent and search

Now what google will do, it will search its entire database and try to match with those that best describe your entered keywords and return it to you.

What if you knew that in my blog there is a post about intent that badly describe about intent and still you wanna see that, then you will probably enter my blog address in your browser url instead of going to google. Though it’s not a bad idea to go to google for various type of information. At least I would do that. 🙂

In first case what did you do?

You did give some data to google and google fired something at you when it found something using that data.

This will be implicit since you didn’t know where in the world has a server which reside the appropriate data in terms your given data.

In the second case you did know explicitly where can you find your data, so you explicitly told your browser to take you there.

And that is also the case for android too.

Intent intent=new Intent(Intent.ACTION_PICK,
Uri.parse("content://contacts/"));
startActivityForResult(intent,PICK_CONTACT);

is used with implicit intent. As you can see here, in creating new intent we need an action and the data that action will be performed on. Now startActivityForResult will launch the activity that uses “content://contacts/” kind of data. As for the action though you don’t know if they don’t tell you what kind of action is permitted on that application’s activity but we know in the case we are using now because Intent.ACTION_PICK is supported by android’s own contact application so this intent will launch android’s native contact application where we can pick a contact that we choose and return with the result in your activity. As with previous example here you only knew what kind of data you needed what you wanna do with that data, now android will lookup for an appropriate application that uses this kind of data and also permit the kind of action you are requesting since some application’s data will not be available to others to use. If any appropriate application is found android will start that activity and show it to you to do your work.

As of explicit:


Intent intent=new Intent(PageOne.this,PageTwo.class);
startActivity(intent);

You can easily guess that in here I’m in page one and I want to go another activity that is page two.

Here I explicitly told which activity I want to start.

Notice that I used startActivityForResult for the first one and startActivity for the second one, this may confused you a little bit, I will explain it to you later.

I think that explain not much but little bit about intent.

It will be more clear if you see some example application.

Using Implicit Intent:  ContactPicker

Using Explicit Intent: ReportGenerator

or you can check it from here:
svn checkout http://reportgenerator.googlecode.com/svn/trunk/

this entire application uses explicit intent to go from one page to another.

Thank you for checking by and  if you have any question or suggestion please do comment. I appreciate that very much.

“HAVE A GOOD PROGRAMMING“

Categories: Android

Difference between interface and abstract in OOP

October 11, 2010 Leave a comment

Now what is interface really?Interface is kind of like template.In that you tell people what standard they should follow but not telling them how to.For example.. assume you create box when people order it to you.In that case every  time they order a box with telling you ”i want some box like that you made for my neighbour”  then you define properties and  behaviour of box yourself.After some days your  workload has been so overflowed that you have to open your own company and need to recruit some worker in that company.And later you’ve to open some branches for it.Now in that case again when order comes to you ,you are not going to go to the every branch to do the job.You need to give some kind of standard to the branch manager’s or ceo whatever you call about how they should  make a box.Give them some template of box where you define what a box should behave when they create it.Tell them something like this:

public interface boxTemplate{

double setWidth(double w);

void getWidth();

double setHeight(double h);

void getHeight();

double setLength(double l);

void getLength();

double getArea();

}

And then one of the branch,design a box class something like this:

public class box1 implements boxTemplate{

public double width;

public double height;

public double length;

public box1(double wd,double hg,double ln){

this.setWidth(wd);

this.setHeight(hg);

this.setLength(ln);

}

public void setWidth(double w){

this.width=w;

}

public    double getWidth(){

return width;

}

public    void setHeight(double h){

this.height=h;

}

public    double getHeight(){

return height;

}

public    void setLength(double l){

this.length=l;

}

public    double getLength(){

return length;

}

public    double getArea(){

return (width*height*length);

}

}

No matter how all branches want to make a box, should always follow your template .Box class design of different branches can differ from one another but since they all are implementing your boxTemplate you know that what behavior a box can behave when it’s ready no matter what it’s origin is.

Abstract:

One day somehow you get a huge order of making box but with some condition.By imagining that you can be next millioniare you accepted those condition.Now the condition was that they want box with same width and length but with red,orange,yellow,green,black,white  in  color and different type of height.Since it’s a big order  you call your three branch manager.And give all of them a new kind of template like this:

abstract class boxNewTemplate {

public double width=22.0;

public double length=22.0;

boxNewTemplate()

{

this.setWidth(this.width);

this.setLength(this.length);

}

public void setWidth(double w){

this.width=w;

}

public    double getWidth(){

return width;

}

public    void setLength(double l){

this.length=l;

}

public    double getLength(){

return length;

}

abstract void setHeight(double h);

abstract double getHeight();

abstract void setColor(int colorCode);

abstract double getArea();

}

And then tell one of them to make boxes where half of them should be red and half orange and you also told the same to others for making other colors.After that one of them create a box class like this:

public class box2 extends boxNewTemplate{

static final int RED=1;

static final int ORANGE=2;

public double height;

public box2(double hg,int colorCode) {

super();

this.setHeight(hg);

this.setColor(colorCode);

}

public  void setHeight(double h){

this.height=h;

}

public    double getHeight(){

return height;

}

public    double getArea(){

return (width*height*length);

}

public void setColor(int colorCode){

if(colorCode==RED){

//give the color

}else if(colorCode==ORANGE){

//give the color

}else{

//do nothing

}

}

}

So the meaning of abstract class is that you do some implementation of your own to a class but some of them you leave for others.So if someone wants to include your class in their system they just have to implement those things that you did not in that class and you do that by telling them it’s abstract.Now if a method is not implemented yet which is abstract but most of the method of that class are how they are going to know that some of this class’s mehod is not implemented yet if you do not put abstract  before that class name.Think about it.

I think that explains a lot about interface and abstract.

Again what you are reading in here is the concept that i figure out myself.It can contain any or many conceptual error.If you find some,feel free to tell me about it.And also if you have any question feel free to ask.

HAVE A GOOD PROGRAMMING

Categories: Java, OOP Tags: ,

Concept of Object in OOP

October 9, 2010 Leave a comment

When we  first try to learn java(Object Oriented Programming),we all must have a conflict with Object.To be a developer having the idea about,”what is object?” is must.You must have a basic understanding about Object.Cz ,by the time pass by you will see that all things ,if it gui or others it always end up with concept of Object.So it is really very very important to have clear concept of Object Oriented Programming.

Now when u try to understand oop the very first question comes in mind is that What is this Object means?

Object is something that has some properties.And has some behaviour that acts with those properties.I am going take an example of Box.Now a box is cube like thing.It has width,height,length.If you assume those are it’s properties then i will say finding it’s area can be considered as it’s behaviour .Again if you are still confused about behaviour now what is behaviour in plain text?Think about yourself.Can you feel your skin?… J of course you can.When it is cold what do u do?And when it is summer i don’t think you do same thing as you do at the time of winter.So i can say the behaviour of your ,change when the behaviour or properties of something other change.See deep inside this concept,the behaviour change of weather will change the body temperature property of your thus your behaviour will also change.Go back to the box.If you change any property of it,it will affect the area of it.Now you can think of as many as behaviour you can.It’s up to u.If someone told you that i want some box with different type of area and also with different type of color.Then you can add a property of color with also add one extra behaviour in it that is going to set it’s color.You can imagine anything as object.From electron to whole universe.Since you are probably not here to assume the whole world as object but  to understand object in respect to programming language.What about a window or the browser you are seeing or a button?All can be imagined as object.A window has title bar, closing option,minimizing option e.t.c.When you click on minimize, it’s behaviour should be minimizing the window.What about the properties clicking on it?Clicking on it will fire a change in properties will fire to it’s corresponding behaviour.Take another example of human.The lowest distance of human eye that it can see is 25cm.Now if you are wearing a glass or your friend is,tell yourself or him what happened why are you wearing a glass?Probably the answer will be lowest distance of eye has been reduced or increased.So if i tell you lowest _distance is a property of another property (can also be considered  as object itself)of human which is eye.Well sometimes creator create human’s with a defected eye or  anything can happen to one’s eye.Every human has a property of eye and it can be true or false depends on ,if it can see or not.Now the behaviour of eye is to see something where it has a property of seeing something with minimum distance of 25cm.If this 25cm is changed by some another behaviour then it will fire a change in the lowest_distance thus the behaviour  of eye change thus you or your friend or your neighbour wear a glass of plus or minus power.

I think that’s explain a lot what the object is.

One thing you should know that what you are reading in here is the concept that i figure out myself.It can contain any or many conceptual error.If you find some,feel free to tell me about it.And also if you have any question feel free to ask.

And “HAVE A GOOD PROGRAMMING

 

Categories: Java, OOP Tags: ,