Showing posts with label Interface. Show all posts
Showing posts with label Interface. Show all posts

Tuesday, 27 September 2011

Interface And Abstraction – Spiritual Explanation

“What is the difference between interface and abstract class?”, a typical interview question . Answer is so obvious, and we can list at least 3 differences. Here is an attempt to correlate Object Oriented world with spiritual world, and explain abstraction and interface.

“Soul is an abstract notion realized by concrete living being”. So as per OO world, if you got “Soul” as abstract class, you got to have a concrete class “Life”. Soul can not operate without Life.
Just like I said object is an entity with an objective to live, abstract class can live through concrete class. Inheritance is the only mechanism for an abstract class to live. Spiritually, Soul operates through life. Life is an object with a process thread running in it.

In Spiritual world, it is said that “Soul carries the karma (good or bad actions) from previous life, which has influences in the new life”. If you consider this statement, karma is the action log recorded into the abstract class.
Body is an interface to life (and hence interface to Soul) and real world. so IBody can be implemented by body of human, bird or any living creature. Once the objective is complete in this real world, destructor is called on life object. However actions are kept recorded (like log files) in the abstract class through out this new life.
In every new life actions recorded in abstract class is not revealed, as it is private declaration . Only the ultimate object builder (God)  has access to it. Object builder reads this private variable, and makes the decision of choosing a new interface for Soul. Dispose method is programmed to be called in a timer function. When timer event fires, dispose is called, and the Life object is disposed terminating the process thread.

After thread is terminated and Life is disposed, Object builder reads the record log from Soul class. Based on the karma recorded in the log, a new object with the suitable interface (body) is created, and Life is induced into it with a process thread. And a timer is started in the Life class, which when fires Thread Abort is called.

Friday, 1 July 2011

Writing Generic interface

A class or an interface is generic if it has one or more type variable. Type variable are delimited by angle brackets and follow the class (or the interface) name:

public interface List<T> extends Collection<T> {
  ...
}

Roughly speaking, type variables act as parameters and provide the information the compiler needs to make its checks.

Many classes in the Java library, such as the entire Collections Framework, were modified to be generic. The List interface we've used in the first code snippet, for example, is now a generic class. In that snippet, box was a reference to a List<Apple> object, an instance of a class implementing the List interface with one type variable: Apple. The type variable is the parameter that the compiler uses when automatically casting the result of the get method to an Apple reference.

In fact, the new generic signature or the get method of the interface List is:

T get(int index);

The method get returns indeed an object of type T, where T is the type variable specified in the List<T> declaration.

Friday, 22 April 2011

Inheritance among interfaces in java

Note the exception of extends with Interfaces
It is possible to use derivation in the definition of interfaces. And in Java it is possible for an interface to extend more than one base interface:
interface D extends E, F
{
}
 
In this case, the derived interface D comprises all the methods inherited from E and F as well as any new methods declared in the body of D.

Interfaces in java

Interfaces are similar to abstract classes but all methods are abstract and all properties are static final. Interfaces can be inherited (ie. you can have a sub-interface). As with classes the extends keyword is used for inheritence.Java does not allow multiple inheritance for classes (ie. a subclass being the extension of more than one superclass). An interface is used to tie elements of several classes together. Interfaces are also used to separate design from coding as class method headers are specified but not their bodies. This allows compilation and parameter consistency testing prior to the coding phase. Interfaces are also used to set up unit testing frameworks.
As an example, we will build a Working interface for the subclasses of Animal. Since this interface has the method called work(), that method must be defined in any class using the Working interface.

public interface Working
{
  public void work();
}

When you create a class that uses an interface, you reference the interface with the phrase implements Interface_list. Interface_list is one or more interfaces as multiple interfaces are allowed. Any class that implements an interface must include code for all methods in the interface. This ensures commonality between interfaced objects.


public class WorkingDog extends Dog implements Working
{
  public WorkingDog(String nm)
  {
    super(nm);    // builds ala parent
  }
  public void work()  // this method specific to WorkingDog
  {
    speak();
    System.out.println("I can herd sheep and cows");
  }
}


Also see Multiple inheritance in java

Sunday, 17 April 2011

Defining an user-defined marker interface in Java

Let's define a user-defined marker interface. Let's say there is an app suporting a medical store inventory and suppose you need a reporting showing the sale, revenue, profit, etc. of three types of medicines - allopathic, homeopathic, and ayurvedic separately. Now all you need is to define three marker interfaces and make your products (medicines) implement the corresponding ones.

public interface Allopathic{}
public interface Homeopathic{}
public interface Ayurvedic{}

Now we can use instanceof operator, to which interface is used. So its not of much use for JVM, but still we can use it for our own use.

for (Medicine medicine : allMedicines) {
if (medicine instanceof Allopathic) {
//... update stats accordingly
}
else if (medicine instanceof Homeopathic) {
//... update stats accordingly
}
else if (medicine instanceof Ayurvedic) {
//... update stats accordingly
}
else {
//... handle stats for general items
}
}

As you can see the medicines themselves don't need to implement any specific behavior based on whether they are allopathic, homeopathic, or ayurvedic. All they need is to have a way of reflecting which category they belong to, which will in turn help the reporting modules to prepare the stats accordingly.

Now this can be done by having a flag as well... yeah, sure it can be. But, don't you think tagging a class makes it more readable than having a flag indicating the same. You kind of make it an implementation-independent stuff for the consumers of your classes. If your class implements an interface, it becomes part of the class signature of the published API. Otherwise, you would probably handle the situation by having a public final field having the flag set up at the time of instantiation - final because you would not like others to change it. I guess going the marker interface way would probably make more sense in many such situations.

Another advantage of going via marker interface way is that at any point of time you can easily cast the objects of the implementing classes. Again it's not that if you go via public final approach, you can't do that. You can very well do, but casting might look a cleaner approach in many situations.

The bottom-line is there will hardly be any enforced need for a designer/developer to go via that way as there can be possible alternatives, but marker interfaces can surely be a preferred choice for some in some cases.


What is a java marker interface?

Java marker interface has no members in it. Marker interface ‘was’ used as a tag to inform a message to the java compiler.

Java Marker Interface Examples:
java.lang.Cloneable
java.io.Serializable
java.util.EventListener

Lets take the java.io.Serializable marker interface. It doesnot has any members defined it it. When a java class is to be serialized, you should intimate the java compiler in some way that there is a possibility of serializing this java class. In this scenario, marker interfaces are used. The java class which may be serialized has to implement the java.io.Serializable marker interface. In such way, we are intimating the java compiler.

From java 1.5, the need for marker interface is eliminated by the introduction of the java annotation feature. So, it is wise to use java annotations than the marker interface. It has more feature and advantages than the java marker interface.


Thursday, 31 March 2011

Abstract classes vs interfaces

Abstract classes
Interfaces
Abstract classes are used only when there is a “is-a” type of relationship between the classes.
Interfaces can be implemented by classes that are not related to one another.
You cannot extend more than one abstract class.
You can implement more than one interface.
Abstract class can implemented some methods also.
Interfaces can not implement methods.
With abstract classes, you are grabbing away each class’s individuality.
With Interfaces, you are merely extending each class’s functionality.

But in the end a good design only matters. See abstract interfaces.

Sunday, 20 February 2011

Constant interface

Constant interface contains no methods but it consists solely of static final fields, each exporting a constant. Classes using these constants implement the interface to avoid the need to qualify constant names with a class name. Here is an example:

// Constant interface pattern - do not use!
public interface PhysicalConstants {
// Avogadro's number (1/mol)
static final double PLANCK_CONSTANT = 6.62e-34;
// Boltzmann constant (J/K)
static final double BOLTZMANN_CONSTANT = 1.3806503e-23;
// Mass of the electron (kg)
static final double ELECTRON_MASS = 9.10938188e-31;
}

The constant interface pattern is a poor use of interfaces. That a class uses some constants internally is an implementation detail. Implementing a constant interface causes this implementation detail to leak into the class's exported API. It is of no consequence to the users of a class that the class implements a constant interface. In fact, it may even confuse them.


Worse, it represents a commitment: if in a future release the class is modified so that it no longer needs to use the constants, it still must implement the interface to ensure binary compatibility. If a nonfinal class implements a constant interface, all of its subclasses will have their namespaces polluted by the constants in the interface.There are several constant interfaces in the java platform libraries, such as java.io.ObjectStreamConstants. These interfaces should be regarded as anomalies and should not be emulated.


If you want to export constants, there are several reasonable choices. If the constants are strongly tied to an existing class or interface, you should add them to the class or interface. For example, all of the numerical wrapper classes in the Java platform libraries, such as Integer and Float, export MIN_VALUE and MAX_VALUE constants. If the constants are best viewed as members of an enumerated type, you should export them with a typesafe enum class. Otherwise, you should export the constants with a noninstantiable utility class. Here is a utility class version of the PhysicalConstants example above:

// Constant utility class
public class PhysicalConstants {
private PhysicalConstants() { } // Prevents instantiation
public static final double PLANCK_CONSTANT = 6.622e-34;
public static final double BOLTZMANN_CONSTANT = 1.3806503e-23;
public static final double ELECTRON_MASS = 9.10938188e-31;
}

So we make constructor private and fields static.


While the utility class version of PhysicalConstants does require clients to qualify constant
names with a class name, this is a small price to pay for sensible APIs. It is possible that the
language may eventually allow the importation of static fields. In the meantime, you can
minimize the need for excessive typing by storing frequently used constants in local variables
or private static fields, for example:

private static final double PI = Math.PI;
In summary, interfaces should be used only to define types. They should not be used to export constants.

Abstract-Interface or skeletal implementations

You can combine the virtues of interfaces and abstract classes by providing an abstract skeletal implementation class to go with each nontrivial interface that you export. So abstract class provides basic functionality, but interface adds to it and we get skeletal implementation or abstract-Interface.

Interfaces are ideal for defining mixins

A mixin is a type that a class can implement in addition to its “primary type” to declare that it provides some optional behavior. For example, Comparable is a mixin interface that allows a class to declare that its instances are ordered with respect to other mutually comparable objects. Such an interface is called a mixin because it allows the optional functionality to be “mixed in” to the type's primary functionality.
Abstract classes cannot be used to define mixins for the same reason that they can't be retrofitted onto existing classes: A class cannot have more than one parent, and there is no reasonable place in the class hierarchy to put a mixin.

Generally speaking mixins provide some additional support and they have interface which generally ends with "able". Ex. comparable, callable, iterable and so on.

Sunday, 26 September 2010

Multiple Inheritance in Java

In Java a class can be derived from only one base class. That is, the following declaration is not allowed:
class C extends A, B // Wrong;
{
}
Nevertheless, it is possible for a class to extend a base class and to implement one or more interfaces:
class C extends A 
implements D, E
{
}
 
The derived class c inherits the members of A and it implements all the methods defined in the interfaces D and E.

Inheritance among interfaces in java