The most successful people in any walks of lives may not be the most talented ones but are definately the most passionate & dedicated ones.

Thursday, September 16, 2010

Factory design pattern [with sample implementation in java]

Definition -- Factory design pattern
Provides an abstraction (usually via an interface) and lets subclass / implementing classes decide which class / method should be instantiated / called, based on the conditions or parameters given.

Intent :-
Factory Method lets a class defer instantiation to subclasses.
To delegate responsibility among different objects and this kind of partitioning is good since it encourages Encapsulation and Delegation.

Discussion :-
Lets leave aside java concepts for a moment and think what a factory in general does? Yes, ask this question to yourself that what any typical factory [say a Toy factory which makes different kind of toys some in shape of aeroplane, some in shape of a racing car] functions?

Now what a factory owner will do to maximize his profit and allow new toys to be build seamlessly is exactly the same what we are going to do in our java classes.

What the toy factory owner will do is that in one chamber of the factory, he will have molten plaster-of-paris (or other material) and then bring it to another chamber where he has kept different toy structures like in the shape of aeroplane / jeep etc and then pour the molten plaster-of-paris into those structures and when it solidifies, he gets the toy of that shape. So the molten plaster-of-paris doesn't know until at the end moment that which structure it would be poured in and what toy would come out but then for sure it would be a toy.

Now lets see how we utilize this concept in java. The molten plaster-of-paris is equivalent to a interface i.e. a standard agreement that it can be converted into any toy provided its poured into a shape/structure.
The structures of aeroplane/jeep are the concrete subclasses which implement the contract with the molten P-o-P. Now what toy would turn out is not known until its poured is similar to getting the objects at runtime.

This we can say that...
Factory Method is to creating objects <==is similar to==> Template to implementing an algorithm/rule [molten P-o-P into structures].
In technical terms, A superclass specifies all standard and generic behavior and then delegates the creation details to subclasses that are supplied by the client.

Why to use Factory design pattern?
We would use a pattern only if its benefits us/our solution in some way or the other. So benefits of Factory pattern are:-
  • A family of objects is separated by using shared interface.
  • Hide concrete classes from the client.
  • The advantage of a Factory Method is that it can return the same instance multiple times, or can return a subclass rather than an object of that exact type.
  • The "new" operator is considered harmful. There is a difference between requesting an object and creating one. The "new" operator always creates an object, and fails to encapsulate object creation. A Factory Method enforces that encapsulation, and allows an object to be requested without inextricable coupling to the act of creation.
Where to use a Factory pattern?
  • A class cannot anticipate its subclasses, which must be created.
  • A sample scenario:- One typical use of the Factory Pattern in an Enterprise JavaBean (EJB) Application: An entity bean is an object representation of persistent data that are maintained in a permanent data store, such as a database. A primary key identifies each instance of an entity bean. Entity beans can be created by creating an object using an object factory Create method. Similarly, Session beans can be created by creating an object using an object factory Create method.
Sample implementation of Factory pattern [in java programming language] :-
  • Here, I have used 6 [classes and interfaces] to provide a sample implementation.
  • The purpose of each class and interface is explained at the beginning of the source code along with other important points.
  • Here you can begin looking at FactoryPatternDemo.java class which has the main() method as a starting point.

(1) ************ start of Constants.java ************
/**
* Purpose:- Class to accomodate constants at one place.
*/
package factoryPattern;

/**
* @author Vinay K Mudgil
*
*/
public class Constants {

public static final String CONSOLE_LOG = "consoleWriter";
public static final String FILE_LOG = "fileWriter";

public static final String logFileName = "TestLogFile.log";
public static final String logFileLocation = "/home/vm234069/Desktop/";
}
************ end of Constants.java ************


(2) ************ start of ConsoleLogWriter.java ************
/**
* Purpose:- The usage of this class is to implement the console logging functionality
*/
package factoryPattern;

/**
* @author Vinay K Mudgil
*
*/
public class ConsoleLogWriter implements ILogWriter {

private boolean isDebugModeOn = false;

public void setDebugMode(boolean value) {
this.isDebugModeOn = value;
}

public void printErrorStatement(String errMsg) {
if (isDebugModeOn)
System.out.println("Printing error message on console.");
}

public void printDebugStatement(String debugMsg) {
if (isDebugModeOn)
System.out.println("Printing debug message on console.");
}

}
************ end of ConsoleLogWriter.java ************

(3) ************ start of FactoryPatternDemo.java ************
/**
* Purpose:- To demonstrate factory pattern.
*/
package factoryPattern;

/**
* @author Vinay K Mudgil
*
*/
public class FactoryPatternDemo {

public static void main(String[] args) {

//First lets write to a console.
ConsoleLogWriter clg = (ConsoleLogWriter) LogFactory.getLogWriter(Constants.CONSOLE_LOG);
clg.setDebugMode(true);
clg.printDebugStatement("debug message");
clg.printErrorStatement("error message");

//now lets write to a log file.
FileLogWriter flw = (FileLogWriter) LogFactory.getLogWriter(Constants.FILE_LOG);
flw.setDebugMode(true);
flw.openLogFile();
flw.printDebugStatement("debug message");
flw.printErrorStatement("error message");
flw.closeLogFile();

}

}
************ end of FactoryPatternDemo.java ************


(4) ************ start of FileLogWriter.java************
/**
* Purpose:- The usage of this class is to implement the console logging functionality
*/
package factoryPattern;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

/**
* @author Vinay K Mudgil
*
*/
public class FileLogWriter extends Constants implements ILogWriter{

private boolean isDebugModeOn = false;
private BufferedWriter bw = null;


public void openLogFile() {
try {
bw = new BufferedWriter(new FileWriter(logFileLocation+logFileName));
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}


public void setDebugMode(boolean value) {
this.isDebugModeOn = value;
}


public void printErrorStatement(String errMsg) {
try {
if(bw != null) {
bw.write(errMsg+" -- Printing error message in log file.\n");
bw.flush();
}
} catch (IOException ioe) {
System.out.println("IOException via writing error Message");
} catch (Exception e) {
System.out.println("Exception via writing error Message");
}
}

public void printDebugStatement(String debugMsg) {
try {
if(bw != null) {
bw.write(debugMsg +" -- Printing debug message in log file.\n");
bw.flush();
}
} catch (IOException ioe) {
System.out.println("IOException via writing debug Message");
} catch (Exception e) {
System.out.println("Exception via writing debug Message");
}

}

public void closeLogFile() {

try {
if(bw != null) {
bw.close();
}
} catch (IOException ioe) {
System.out.println("IOException while closing the file.");
}
}

}

************ end of FileLogWriter.java ************


(5) ************ start of ILogWriter.java ************
/**
* Purpose:- The purpose of this interface is to provide an agreement of some basic functionalities which any generic
* LogWriter should provide
*/
package factoryPattern;

/**
* @author Vinay K Mudgil
*
*/
public interface ILogWriter {

//turn on/off the debug mode
public void setDebugMode(boolean value);

//write an error statement
public void printErrorStatement(String errMsg);

//write an debug statement
public void printDebugStatement(String debugMsg);

} //enf of Interface definition
************ end of ILogWriter.java ************


(6) ************ start of LogFactory.java ************
/**
* Purpose:- This is the factory class which actually creates the concrete class type depending on which is required by the client.
*/
package factoryPattern;

/**
* @author Vinay K Mudgil
*
*/
public class LogFactory extends Constants {

// method returning appropriate class object
public static ILogWriter getLogWriter(String writerType) {
if (writerType.equals(Constants.CONSOLE_LOG)) {
return new ConsoleLogWriter();
} else if (writerType.equals(Constants.FILE_LOG)) {
return new FileLogWriter();
}

System.out.println("illegal logging selection...");
return null;
}
}

************ end of LogFactory.java ************

Please feel free to comment on concepts 'n' sample code snippet provided above & spare me for any typo's. Happy to learn !!!

Thanks !!!

Tuesday, September 14, 2010

kiss - Prototype design pattern

Before I start let me make kiss very clear. Its an acronym for "keep it short & simple". I found this pattern fairly interesting and in fact got into the realm of "cloning" in java due to this, so thought to share my learning and experiences on this design pattern.

What is a prototype design pattern?
In this point we should be exploring the intent of the prototype design pattern, which is :-
  • It specifies the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.
  • This pattern co-opt one instance of a class for use as a breeder of all future instances.
  • This pattern sees the java "new" operator as cumbersome.
Okayy, the jist is, we create an object of a class once & then clone the object another instance is required.


Why to use prototype design pattern?
We would use a pattern only if its benefits us/our solution in some way or the other. So benifits of prototype pattern are:-
  • Whenever object initialization is expensive [of-course to the compiler in terms of time 'n' resources] and you anticipate few variations on the initialization parameters, there this pattern could be used.
  • It allows a developer to add / remove attributes at runtime.
  • It allows a developer to specify new objects in terms of varying values.

Where to use a prototype pattern?
  1. When there are many subclasses that differ only in the kind of objects.
  2. A sample scenario:- "There are two class instance(say) that need to be populated with some values, retrieved from the database.The first instance contains values sorted on some key value,while the other is sorted base on some other key(but containing the same data). Now there can be two mechanism for fulfilling the above requirement:- a) Sort the values from the database and then populate in the class,hence the database retrieval is performed 2 times(or n times for n instances). Or b) get the values from the database(one time), populate a single instance, override the clone() method,and then perform cloning."

Sample implementation of prototype pattern [in java programming language] :-
  • Here I have used 8 [classes and interfaces] to provide a sample implementation.
  • The purpose of each class and interface is explained at the beginning of the source code along with other important points.
  • Here you can be starting at PrototypeDemo.java class which has the main() method as a starting point.

(1) ************ start of Constants.java ************
/**
* Purpose:- To place constants used through-ouot the example for Prototype pattern at one place.
*/

package prototypePattern;

/**
* @author Vinay K Mudgil
*
*/
public class Constants {

public static final String SQUARE = "Square";
public static final String TRIANGLE = "Triangle";
public static final String RECTANGLE = "Rectangle";

public static final int numOfMasterObjects = 10;

}
************ end of Constants.java ************


(2) ************ start of Prototype.java ************
/**
* Purpose:- The purpose of this class is to provide an agreement (thereby abstraction also) so that the class which implement this
* interface have to override the declared methods.
*
* Notes:- (1) By default (implictly) interface members are public, static and final i.e. they are constants and coan't be modified.
* (2) They support the concept of multiple inheritence.
*/

package prototypePattern;

/**
* @author Vinay K Mudgil
*/

public interface Prototype {

//The purpose is to get the name which is to be cloned.
public String getName();

//The purpose is that class implementing this interface should override the clone method.
public Object clone() throws CloneNotSupportedException;
}

************ end of Prototype.java ************


(3) ************ start of PrototypeDemo.java ************
/**
* Purpose:- Class which is used to show the "prototype" pattern in java works :)
* i.e. its a client application which uses a prototype design pattern
*/

package prototypePattern;

/**
* @author Vinay K Mudgil
*
*/
public class PrototypeDemo {

//used to load the
public static void loadMasterObjectsAtBegining() {
ProtoTypeMaster.addPrototype(new Triangle());
ProtoTypeMaster.addPrototype(new Square());
ProtoTypeMaster.addPrototype(new Rectangle());
}

public static void main(String[] args) throws CloneNotSupportedException {
System.out.println("starting execution now.....");
Object [] clonedObjectArray = new Object[args.length];
int count=0;

//intialize
PrototypeDemo.loadMasterObjectsAtBegining();

//For each command-line argument, lets see if we can create a clone.
for(int i=0;i if( (ProtoTypeMaster.findAndClone(args[i]) ) != null) {
clonedObjectArray[count] = ProtoTypeMaster.findAndClone(args[i]);
count++;
}

}

//now, just for sample, lets execute draw method to show that we created cloned objects.
for(int i=0; i if (clonedObjectArray[i] != null)
((UtilityFunctions) clonedObjectArray[i] ).draw();
}

} //end of main method

}//end of class
************ end of ************


(4) ************ start of ProtoTypeMaster.java************
/**
* Purpose:- To hold objects of class which are to be cloned.
*/

package prototypePattern;

/**
* @author Vinay K Mudgil
*
*/

public class ProtoTypeMaster extends Constants{

private static Prototype [] masterObjectHolder = new Prototype [Constants.numOfMasterObjects];

//variable which holds the current count of
private static int currentCount = 0;

/*
* Purpose:- Add relevant object to the masterObjectHolder
*/
public static void addPrototype(Prototype pObj) {

if(currentCount < Constants.numOfMasterObjects)
masterObjectHolder[currentCount++] = pObj;
else
System.out.println("This Addition would exceedes max. number of allowed objects which can be Prototyped and hence rejecting this addition");
} //end of addPrototype() method


/*
* Purpose:- To search for the relevant class to be cloned and then clone that class and return the cloned instance.
*/
public static Object findAndClone (String classNameToBeCloned) throws CloneNotSupportedException {

//first search in the masterObjectHolder that which relevant class is to be cloned
for(int i=0; i < currentCount; i++) {

if ( masterObjectHolder[i].getName().equals(classNameToBeCloned) ) {
//now that our search is successful, lets clone the object and return it.
return masterObjectHolder[i].clone();
}
}

System.out.println("class name which you supplied at \"runtime\" couldn't be found in the masterObjectHolder and hence can't be cloned");
return null;
}


} //end of class
************ end of ProtoTypeMaster.java ************


(5) ************ start of Rectangle.java ************
/**
* Purpose:- To provide a class (for testing) which can be cloned.
*/
package prototypePattern;

/**
* @author Vinay K Mudgil
*
*/
public class Rectangle extends Constants implements Prototype, UtilityFunctions, Cloneable {

public String getName() {
return Constants.RECTANGLE;
}

public void draw() {
System.out.println("Drawing a Rectangle");
}

public Object clone() throws CloneNotSupportedException {
return (Rectangle) super.clone();
}

}//end-of-class
************ end of Rectangle.java ************


(6) ************ start of Square.java ************
/**
* Purpose:- To provide a class (for testing) which can be cloned.
*/
package prototypePattern;

/**
* @author Vinay K Mudgil
*
*/
public class Square extends Constants implements Prototype, UtilityFunctions, Cloneable {
public String getName() {
return Constants.SQUARE;
}

public void draw() {
System.out.println("Drawing a Square");
}

public Object clone() throws CloneNotSupportedException {
return (Square) super.clone();
}

}//end-of-class
************ end of Square.java ************


(7) ************ start of Triangle.java************
/**
* Purpose:- To provide a class (for testing) which can be cloned.
*/

package prototypePattern;

/**
* @author Vinay K Mudgil
*
*/

public class Triangle extends Constants implements Prototype, UtilityFunctions, Cloneable {
public String getName() {
return Constants.TRIANGLE;
}

public void draw() {
System.out.println("Drawing a Triangle");
}

public Object clone() throws CloneNotSupportedException {
return (Triangle) super.clone();
}

}//end-of-class
************ end of Triangle.java ************


(8) ************ start of UtilityFunctions.java ************
/**
* Purpose:- This interface is created to give you an idea that in real world scenerio's this interface is overridden by class
* to provide their own implementation of a methods
*/

package prototypePattern;

/**
* @author Vinay K Mudgil
*
*/

public interface UtilityFunctions {

//sample method which every first concrete sub-class would provide an implementation for.
public void draw();
}
************ end of UtilityFunctions.java ************


Please feel free to comment on concepts &
sample code snippet provided above. Happy to learn from you.

Thanks !!!

Monday, September 13, 2010

At times Idioms leave you perplexed !!!

Here are a few idioms that I learned today...
  • Tongue in Cheek :- Saying something in an amusing / ironical way or tone, not to be taken seriously.
  • Bury in Hatchet :- Settle one's differences, make peace.
  • Out of frying pan and into the fire :- From a bad situation to worse.
  • To make a clean breast of :- to tell the truth about esp. something wrong you have done , to confess your wrong doing.
Here are a few with [M]eanings and [U]sage:-

(1) A pocket of resistance :-
[M] A few people resisting, only a few people on the other side
[U] Their is a pocket of resistance in one district, a few disagree

(2) A poker face :-
[M] A face with no expression, showing no emotion
[U] Most of the times in the field, M S Dhoni shows a poker face

(3) A red letter day :-
[M] A memorable day, a special day
[U] This is going to be a red letter day, I found my lost keys.

(4) A redneck :-
[M] A person who is intolerant of other opinions and cultures, a bigot
[U] Well if you ask a redneck he will say, "Find a job or starve-- and if you don't like it, too bad !!!"

(5) A raw deal :-
[M] An unfair deal/contract
[U] If he's charging too much rent, then believe me that you are getting a raw deal.

(6) A run for your money :-
[M] Tough competition, strong opponent
[U] I would enter this election and give him a run for his money

(7) A rolling stone gathers no moss
[M] A person who is always moving has few possessions
[U] It seems that you have always been a rolling stone

(8) A roll in a hay :-
[M] making love, having sex
[U] I asked her if she wanted to have a roll in a hay, and she said, "Sure. Do you have a condom?"

(9) A riot / A hoot :-
[M] lots of fun, having a good time
[U] You should have gone to Rooney's party. It was a riot.

(10) A scandal is brewing :-
[M] rumors of a scandal, an evil/false story being told
[U] A scandal is brewing in pacific ocean. A shark and a whale are living together without a license.

(11) A score to settle / A bone to pick
[M] An argument to finish
[U] He owes me a month's rent. I have a score to settle with him.

(12) A screw loose / one brick short of a full load :-
[M] a little bit /crazy
[U] At times I think that he has a screw loose, like when he eats paper
[U] I am ok but you might be one brick short of full load. ha ha ha


* the more you know, your hunger for knowledge intensifies !!!

Basics of Indexes in Database Systems

(A) What is an index ?

1. An index is a physical list of values [tuple to be specific in
R-DBMS] that a table contains.
2. It occupies physical space in the database and is as real as the
table and is different from the table [ though a user can't
directly can't reach the index (which could be a table/tree in
itself) ]
3. Hence if you create an index on table1.create_date, for example,
then a file will be created that consists of one row for every
row in table1. Each row contains the create_date and a pointer
back to the row in table1 that the index's row belongs to.
4. Every time you update, delete from, or insert into table1, the
index is also updated, deleted from, or inserted into.

Optimizing our Indexes

1. Creating indexes on char and text fields is not really a good
idea; they work best on fixed length number fields.
2. Every index increases the time in takes to perform INSERTS,
UPDATES and DELETES, so the number of indexes should not be very
much. Try to use maximum 4-5 indexes on one table, not more. If
you have read-only table, then the number of indexes may be
increased.
3. Keep your indexes as narrow as possible. This reduces the size
of the index and reduces the number of reads required to read
the index.
4. If you create a composite (multi-column) index, the order of the
columns in the key are very important. Try to order the columns
in the key as to enhance selectivity, with the most selective
columns to the leftmost of the key.
5. If your application will be performing the same query over and
over on the same table, consider creating a covering index on
the table.
6. Clustered indexes are more preferable than non-clustered, if you
need to select by a range of values or you need to sort results
set with GROUP BY or ORDER BY.

(B) What is a clustered index ?

1. A clustered index is a type of index that re-orders the way
records in the table are physically stored.
2. A table can have only one clustered index.
3. The leaf nodes of a clustered index (almost all the times)
contains actual data pages.
4. By default a clustered index a created with a primary key.

(C) What is a non-clustered index ?

1. A non-clustered index is a type of index in which the logical
order of the index doesn't matches the physical stored order of
the rows in the disk.
2. A table can have more than one non-clustered index.
3. The leaf nodes of a clustered index doesn't contain actual data
pages
4. By default a non-clustered index a created on a unique key

Wish you a happy learning.

Thanks !!!

Differenc between Primary Key and Unique key

The differences between Primary Key and Unique key are as follows.

1) Primary Key is a combination of Unique and not--null constraints, so it can’t have duplicate values or any NULL whereas Unique key can contain null value.

2) A table can have only one PK whereas it can have any number of UNIQUE Key[s].

3) (a) For Oracle UNIQUE Key can have any number of null (because in oracle one null value can't be compared another null value)
(b) For Sybase, I have tested myself that it would not allow null at all in Unique keys
(c) For SQL Server it can have only one NULL (I couldn't get a chance to test this myself)

4) By default Primary Key will generate Clustered Index whereas Unique Key will Generate Non-Clustered Index.


Wish you a happy learning.

Thanks !!!

Monday, August 23, 2010

SingleTon Design Pattern Explained

Definition
One instance of a class or one value accessible globally in an application.

Benefits
Well control the instantiation of a class.
Access to the instance by the way you provided.

Usage
Single window manager
Single printer spooler
Single Input/Output socket
Single log-writer

Sample implementation
**************************class definition starts here**************************
/**
* Purpose :- to implement SingleTon Design Pattern
* Few important points:-
* (a) constructor marked as private
* (b) getSingleTonInstance() is marked as synchronized
* (c) static member & method is used to hold & retrieve (respectivly) the instance.
*/
package singleTonPattern;

/**
* @author Vinay K Mudgil
* @date Aug 23rd 2010
*
*/
public class SingleTonImpl {

/*
* private class-level (static) variable to hold the single instance created.
* initially intialized to null to ensure that object gets created only when its required.
*/
private static SingleTonImpl SingleTonObj = null;



/*
* Private constructor to ensure that this class can't be instantiated via outside [using a new keyword]
*/
private SingleTonImpl() {
//Do nothing -- not required to perform any functions
}


/*
* ----A public class-level method which is visible to all but ensures that only a single object of SingleTonImpl class is created.
* ----This is marked as synchronized to ensure two threads accessing simultaneously shouldn't aceess this and thus eradicating
* possiblity of have more than one object.
*/
public synchronized static SingleTonImpl getSingleTonInstance() {
if (SingleTonObj == null)
SingleTonObj = new SingleTonImpl();

return SingleTonObj;
}



/*
* Overriding clone() method to ensure that object cloning isn't allowed and multiple objects can't be created.
*/
public Object clone() throws CloneNotSupportedException {
//throw appropriate exception
throw new CloneNotSupportedException();
}


}
**************************class definition ends here**************************


Please feel free to comment on this writeup and let me know if nay mistakes you find here in the code snippet or in any of the concepts. Happy to learn !!!

Thank you & keep visiting for more information.
--Vinay

Can we override a static method in java? [Overridding v/s hiding]

Can we override a static method?

This answer is NO, albeit the compiler allows us to write the code which is same as overriding any method in java but the compiler doesn't provides us the benefits of overriding i.e. dynamic object lookup during run-time and hence we say that we can't override static methods in java.

The below explanation would make it crystal clear.

class Foo {
public static void method() {
System.out.println("in Foo");
}
}

class Bar extends Foo {
public static void method() {
System.out.println("in Bar");
}
}
This compiles and runs just fine. Isn't it an example of a static method overriding another static method? The answer is no - it's an example of a static method hiding another static method. If you try to override a static method, the compiler doesn't actually stop you - it just doesn't do what you think it does.

So what's the difference?

Briefly, when you override a method, you still get the benefits of run-time polymorphism, and when you hide, you don't. So what does that mean? Take a look at this code:
class Foo {
public static void classMethod() {
System.out.println("classMethod() in Foo");
}

public void instanceMethod() {
System.out.println("instanceMethod() in Foo");
}
}

class Bar extends Foo {
public static void classMethod() {
System.out.println("classMethod() in Bar");
}

public void instanceMethod() {
System.out.println("instanceMethod() in Bar");
}
}

class Test {
public static void main(String[] args) {
Foo f = new Bar();
f.instanceMethod();
f.classMethod();
}
}
If you run this, the output is

instanceMethod() in Bar
classMethod() in Foo

Why do we get instanceMethod from Bar, but classMethod() from Foo? Aren't we using the same instance f to access both of these? Yes we are - but since one is overriding and the other is hiding, we see different behavior.

Since instanceMethod() is an instance method, in which Bar overrides the method from Foo, at run time the JVM uses the actual class of the instance f to determine which method to run. Although f was declared as a Foo, the actual instance we created was a new Bar(). So at runtime, the JVM finds that f is a Bar instance, and so it calls instanceMethod() in Bar rather than the one in Foo. That's how Java normally works for instance methods.

With classMethod() though. since it's a class method, the compiler and JVM don't expect to need an actual instance to invoke the method. And even if you provide one (which we did: the instance referred to by f) the JVM will never look at it. The compiler will only look at the declared type of the reference, and use that declared type to determine, at compile time, which method to call. Since f is declared as type Foo, the compiler looks at f.classMethod() and decides it means Foo.classMethod. It doesn't matter that the instance referred to by f is actually a Bar - for static methods, the compiler only uses the declared type of the reference. That's what we mean when we say a static method does not have run-time polymorphism.

Because instance methods and class methods have this important difference in behavior, we use different terms - "overriding" for instance methods and "hiding" for class methods - to distinguish between the two cases. And when we say you can't override a static method, what that means is that even if you write code that looks like it's overriding a static method -- it won't behave like an overridden method.

So what about accessing a static method using an instance?

It's possible in Java to write something like:

f.classMethod();

where f is an instance of some class, and classMethod() is a class method (i.e. a static method) of that class. This is legal, but it's a bad idea because it creates confusion. The actual instance f is not really important here. Only the declared type of f matters. That is, what class is f declared to be? Since classMethod() is static, the class of f (as determined by the compiler at compile time) is all we need.

Rather than writing:

f.classMethod();

It would be better coding style to write either:

Foo.classMethod();

or

Bar.classMethod();

That way, it is crystal clear which class method you would like to call. It is also clear that the method you are calling is indeed a class method.

Why does the compiler sometimes talk about overriding static methods?
The Java Language Specification is very clear about the difference between overriding and hiding, even if the compiler messages are not. Sometimes you will see error messages from the compiler that talk about overriding static methods. Apparently, whoever writes these particular messages has not read the Java Language Specification and does not know the difference between overriding and hiding. So they use incorrect and misleading terminology. Just ignore it.


Please correct me if any code snippet / concept is not right and have been inadvertently stated above as a typo.

Happy Learning !!!
--Vinay

Thanks

Java Cloning explained with an example

What is cloning in java?
Cloning refers to creating duplicate copies of objects in java.

What are different flavours of cloning available in java?
We can implement cloning in java in two ways viz. shallow cloning and deep cloning.

Way to achieve this in java
1. Cloning can be achieved in java via the Cloneable interface.
2. Any class which is to be cloned has to implement Cloneable interface.
3. Cloneable interface is a marker interface meaning that it doesn't have methods

Role of the clone() method
1. Member of Object class
2. Method Signature -- protected Object clone() throws CloneNotSupportedException
3. Its a method used to create a copy of an object of a class which implements Cloneable interface.

Know/revise this before you proceed...
(1) The java.lang.Object class defines clone() method that returns a copy of the object (remember to type-cast the object)
(2) Assuming the subclass (which is to be cloned) implements the java.lang.Cloneable interface.
(3) The default behavior of clone() is to return a shallow copy of the object.
(4) Java classes are free to override clone() method to do more complex kinds of cloning.
(5) Cloning of objects can be very useful if you use the "prototype" design pattern or if you want to store an internal copy of an object inside an aggregation class


Concept of shallow cloning:-
(1) In a shalow copy, a new instance of the type is created and the values are copied into the new instance. The reference pointers are copied just like values and hence the reference are pointing to the original objects itself.
(2) If you go ahead and change values in either the original or cloned object's object reference gets reflected at both the places i.e. say for example if you have a class named as "classA" which have (say) three members viz. an int , a float and another reference to a "classB" and you have created an object of "classA" 'n' then cloned it and now if you change any value in "classB" then it will get reflected in the original and the cloned object.

Well if the above statement is confusing to you, then have a look at the below code snippet and all confusion would vanish:-

*******************************code snippet starts here*****************************
/*Note:-
(1) Here classA reffered in above point is "Vector"
(2) Here classB reffered in above point is "StringBuffer"
(3) Here by default, the class "Vector" which we are cloning implements "cloneable" interface so we don't have to implement it explicitly and have simply used the clone() method to clone the object. In case we have a user defined class instead of vector which is to be cloned, we would have been implementing the "cloneable" (a marker interface) as well.
*/

package util.sampleCloning;

import java.util.Vector;
import java.lang.StringBuffer;
import java.lang.Integer;

/**
* @author Vinay K Mudgil
*
*/
public class CloningExample2 {

public static void main(String[] args) {

// make a vector
Vector original = new Vector();

StringBuffer quotation = new StringBuffer("Vinay");
Integer i = new Integer(10);
String str = "abc";

// now add the stringbuffer, Integer and the String valiable to the
// vector created above.
original.add(quotation);

// now clone the Vector object
Vector clone = (Vector) original.clone();

System.out.println("printing \"original\" vector object");
printVectorContents(original);
System.out.print("\n");

System.out.println("printing \"cloned\" vector object");
printVectorContents(clone);
System.out.println("-------------------------------------");


System.out.println("now adding Integer to the original object");
original.add(i);
System.out.println("printing \"original\" vector object");
printVectorContents(original);
System.out.print("\n");

System.out.println("printing \"cloned\" vector object");
printVectorContents(clone);
System.out.println("-------------------------------------");

System.out.println("now adding String to the original object");
original.add(str);
System.out.println("printing \"original\" vector object");
printVectorContents(original);
System.out.print("\n");

System.out.println("printing \"cloned\" vector object");
printVectorContents(clone);
System.out.println("-------------------------------------");

System.out.println("now adding String to the \"clone-ed\" object");
clone.add("Vipin");
System.out.println("printing \"original\" vector object");
printVectorContents(original);
System.out.print("\n");

System.out.println("printing \"cloned\" vector object");
printVectorContents(clone);
System.out.println("-------------------------------------");

System.out.println("SO UNTIL NOW WE ARE HAVING AN IDEA THAT THE CLONED AND THE ORIGINAL OBJECT OF VECTOR CLASS ARE TWO SEPARATE OBJECTS AND WHEN WE ARE ADDING TO ONE, THE OTHER ONE DOESN'T GETS CHANGED...");

System.out.println("-------------------------------------");

System.out.println("now I am modifying the \"text\" object which is of type StringBuffer in original object which is not a primitive but a reference of another class.");
original.add(quotation.append("Kumar Mudgil"));
System.out.println("printing \"original\" vector object");
printVectorContents(original);
System.out.print("\n");

System.out.println("printing \"cloned\" vector object");
printVectorContents(clone);
System.out.println("-------------------------------------");


}// end of main() method

public static void printVectorContents(Vector vecObj) {
for (int i = 0; i < vecObj.size(); i++) {
System.out.println("value at " + i + "-th location is -->"+ vecObj.get(i));
}//end of for-loop
}// end of printVectorContents() method

} // end of class CloningExample2



AND THE OUTPUT OF THIS CODE SNIPPET IS.......


After cloning
Contents of "original":
0 (java.lang.StringBuffer): The quick brown fox

Contents of "clone":
0 (java.lang.StringBuffer): The quick brown fox

--------------------------------------------------------

After adding an Integer to the clone
Contents of "original":
0 (java.lang.StringBuffer): The quick brown fox

Contents of "clone":
0 (java.lang.StringBuffer): The quick brown fox
1 (java.lang.Integer): 5

--------------------------------------------------------

After modifying one of original's elements
Contents of "original":
0 (java.lang.StringBuffer): The quick brown fox jumps over the lazy dog.

Contents of "clone":
0 (java.lang.StringBuffer): The quick brown fox jumps over the lazy dog.
1 (java.lang.Integer): 5


*******************************code snippet ends here*******************************





Concept of deep cloning:-
(1) cloning means creating complete duplicate copy of the original object as well as the sub-objects in the object tree.
(2) Means that if "classA" shares a "has-a" releationship with "classB" and if try to clone an object of "classA" then in that case the cloned object will have a completly new object of "classB" and not mere its reference type.
(3) Also means that if we make any changes in the cloned or original object, the other one doesn't get affected or the changes made are limited to the specific object only.
(4) To implement Deep Copy, we first need to ensure that all the member classes (at all the levels - like if the member class itself has a member of some class type then that class as well... and so on) are implementing the Cloneable interface otherwise calling the clone() method on the objects of those classes will result into CloneNotSupportedException.
-->Once all the member classes implement cloneable, we override the clone() method in all those classes (even in the classes where we have only primitive type members otherwise we would not be able to call the protected clone() method of Object class on the instances of those classes inside some other class)

Below are the example which, if you read carefully, would make deep cloning crystal clear to you.

*******************************classA.java, starts here*******************************
/**
* untility class used to explain the concept of deep cloning
*/
package util.sampleCloning.deepcloning;

/**
* @author Vinay K Mudgil
*
*/
public class classA implements Cloneable{
private int x;
private int y;

public classA(int a, int b) {
this.x = a;
this.y = b;
}

public classA() {
this.x = 100;
this.y = 101;
}


public Object clone() throws CloneNotSupportedException {
return super.clone();
}//end of overridden clone method


public int getX() {
return x;
}

public void setX(int x) {
this.x = x;
}

public int getY() {
return y;
}

public void setY(int y) {
this.y = y;
}



}//end of class

*******************************classA.java, ends here*******************************


*************************DeepCloningImpl.java, starts here*******************************
/**
* class to show sample implementations and concepts of deep cloning
*/
package util.sampleCloning.deepcloning;

/**
* @author Vinay K Mudgil
*
*/
public class DeepCloningImpl implements Cloneable{

public int var;
public classA obj;

public DeepCloningImpl() {
this.var = 200;
this.obj = new classA();
}//end of constructor

public Object clone() throws CloneNotSupportedException {
DeepCloningImpl dci = (DeepCloningImpl) super.clone();
dci.obj = new classA(11,22);

return dci;
}//end of clone method

public static void main(String[] args) {

DeepCloningImpl dciOriginal = new DeepCloningImpl();
DeepCloningImpl dciCloned = null;

System.out.println("Original Object...");
System.out.println("dciOriginal.var -->"+dciOriginal.var);
System.out.println("dciOriginal.obj.getX() --> "+dciOriginal.obj.getX());
System.out.println("dciOriginal.obj.getY() --> "+dciOriginal.obj.getY());


try {
//now cloning the object.
dciCloned = (DeepCloningImpl) dciOriginal.clone();
} catch (CloneNotSupportedException cnse) {
cnse.printStackTrace();
}

System.out.println("\nCloned Object...");
System.out.println("dciCloned.var -->"+dciCloned.var);
System.out.println("dciCloned.obj.getX() --> "+dciCloned.obj.getX());
System.out.println("dciCloned.obj.getY() --> "+dciCloned.obj.getY());

System.out.println("-------------------------------");

System.out.println("Now changing in primitive member of original object and see if cloned object changes...");
dciOriginal.var = 300;

System.out.println("printing Original Object...");
System.out.println("dciOriginal.var -->"+dciOriginal.var);
System.out.println("dciOriginal.obj.getX() --> "+dciOriginal.obj.getX());
System.out.println("dciOriginal.obj.getY() --> "+dciOriginal.obj.getY());

System.out.println("\nprinting Cloned Object...");
System.out.println("dciCloned.var -->"+dciCloned.var);
System.out.println("dciCloned.obj.getX() --> "+dciCloned.obj.getX());
System.out.println("dciCloned.obj.getY() --> "+dciCloned.obj.getY());

System.out.println("-------------------------------");

System.out.println("Now changing in an object which shares a \"has-a releationship\" with original object and see if cloned object changes...");
dciOriginal.obj.setX(500);
dciOriginal.obj.setY(501);

System.out.println("printing Original Object...");
System.out.println("dciOriginal.var -->"+dciOriginal.var);
System.out.println("dciOriginal.obj.getX() --> "+dciOriginal.obj.getX());
System.out.println("dciOriginal.obj.getY() --> "+dciOriginal.obj.getY());

System.out.println("\nprinting Cloned Object...");
System.out.println("dciCloned.var -->"+dciCloned.var);
System.out.println("dciCloned.obj.getX() --> "+dciCloned.obj.getX());
System.out.println("dciCloned.obj.getY() --> "+dciCloned.obj.getY());

System.out.println("-------------------------------");

System.out.println("Now making changes in cloned object and see if original object changes i.e. the other way around of what is done above...");
dciCloned.obj.setX(900);
dciCloned.obj.setY(901);

System.out.println("printing Original Object...");
System.out.println("dciOriginal.var -->"+dciOriginal.var);
System.out.println("dciOriginal.obj.getX() --> "+dciOriginal.obj.getX());
System.out.println("dciOriginal.obj.getY() --> "+dciOriginal.obj.getY());

System.out.println("\nprinting Cloned Object...");
System.out.println("dciCloned.var -->"+dciCloned.var);
System.out.println("dciCloned.obj.getX() --> "+dciCloned.obj.getX());
System.out.println("dciCloned.obj.getY() --> "+dciCloned.obj.getY());

}//end of main() method

}//end of class

*************************DeepCloningImpl.java, ends here*******************************


Happy learning and your critical analysis pertaining to this is welcome (spare me for any typo's).

Thanks !!!

Tuesday, February 23, 2010

The dark tunnel is still to end--part1

Well, I guess its been a long-long time that I posted something new since I started this series of blogs but today my sub-conscious mind replied in affirmation to go ahead and pen down a few things.

Before I proceed further, let me just be honest with myself. The reason why I am writing this blog is that I am feeling utterly frustrated about... what the heck I have done in my life until now?

Soon my mind takes me back to the counseling day when my father "carried" me [yeps I am writing it categorically] to the university campus on the back seat of the scooter...and...I was thinking that [somehow] an engineer is born [yes I still can't believe the fact that I couldn't clear the exam that I wanted-to] but then I wish I still get back my college days.

Now please don't expect me to punch down the name of my first crush as don't you guys think that would be a little too much for me to remember:)

The four years of my engineering were like a free fall from a 100 story building...complete weightlessness... never knew where I was going and what I did during those four years without any idea that why am I here [let me confess that I did some studies in the last semester, believe me it was completely unintentional and got into it just because of some friends]

And once I came near the ground floor, I realized that my engineering was completed though I never tell people that I my specialization is in computer science just to set the expectations right:) but as I already stated in the beginning of this post, I don't want to lie with myself anymore:( and hence mentioning this as well.

And then came a U-turn, I managed to land up myself in a s/w developer job [I don't know what the heck I told those guys who selected me but many thanks to them] and then things changed a little better as I met new people [some good and some not-so-good] and things started to happen for me though the pace seem to be slow.

To know more about me and the jist of my journey until now, watch-out for this space !!!


--Vinay
Anytime @
vinaymudgil007@gmail.com
@yahoo.com
@ANY_GOOD_PUBLIC_DOMAIN_THAT_YOU_CAN_THINK_OK