Tuesday, 27 September 2011
Interface And Abstraction – Spiritual Explanation
Friday, 1 July 2011
Writing Generic interface
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
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
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
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 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 |
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 classpublic class PhysicalConstants {private PhysicalConstants() { } // Prevents instantiationpublic 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:
In summary, interfaces should be used only to define types. They should not be used to export constants.private static final double PI = Math.PI;
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
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