Wednesday, 25 January 2012
Tuesday, 5 July 2011
Mapping Entities with Inheritance
The simplest is to use one table for the whole hierarchy. With this design, each row of the table can hold an object of any type from the hierarchy. There is one column for each of the properties in the union of the sets of properties of all the classes in the hierarchy and there is one
discriminator column which contains a value (usually of type string, character or integer) used to tell which actual type of object is stored in this particular row. One normally does not make this discriminator a property of the class: it is used only by Hibernate to record and detect the type of the object that a row represents.![]() | |
| An Inheritance Class Hierarchy |
<class name="Person" table="people" discriminator-value="P">
<id name="id" column="id" type="long">
<generator class="sequence"/>
</id>
<version name="version" column="version"/>
<discriminator column="subclass" type="character"/>
<property name="dateOfBirth" column="dob" type="date"/>
<property name="name"/>
<property name="gender"/>
<subclass name="Lecturer" discriminator-value="L">
<property name="office" type="string"/>
<property name="telephone" type="string"/>
</subclass>
<subclass name="Student" discriminator-value="D">
<property name="studentID" type="integer"/>
</subclass>
</class>
Here one may not specify any of the subclass fields as not null because the corresponding column will be null in the table for any object of the hierarchy which is not of the subclass that contains the relevant property for that column.
Friday, 24 June 2011
Compiling cyclic dependency in Java
Well, I don’t know what kind of dependency that person had in mind when asking this question – But I had not heard of anything being needed to compile in cases of cyclic dependencies as described below. Check out the code below – At least the current version of Java is clever enough that you need to do nothing special to compile it.
Maybe this was a problem in old versions of Java and interviewers are still stuck looking for answers that are incorrect. Check out the demo code below -
package test;
class A{
A(){
new B();
}
}
package test;
class B{
B(){
new C();
}
}
package test;
class C{
C(){
new A();
}
}
Of course, trying to instantiate any of the above classes would lead to a StackOverflowError.
Saturday, 11 June 2011
How to force the subclasses of a concrete class to override a method?
Though still its not like generating compile time error but gives exception at runtime. Do suggest if you have a better solution.
public class Test{
void test() {
if ((this instanceof Test1)) {
throw new RuntimeException();
}
System.out.println("passed");
}
public static void main(String[] args) {
Test t1 = new Test();
Test1 t2 = new Test1();
t1.test();
t2.test();
}
}
class Test1 extends Test {
}
The output of above program is:
passed
Exception in thread "main" java.lang.RuntimeException
at Test.test(Test.java:5)
at Test.main(Test.java:15)
Tuesday, 24 May 2011
Solution to Square rectangle problem
So inheritance is not always useful, but composition may be the key sometimes.
public class Square
{
private Rectangle r;
public void SetWidth (double x) { r.SetWidth (x); r.SetHeight (x); }
public void SetHeight (double x) { r.SetWidth (x); r.SetHeight (x); }
public void GetWidth () { return r.GetWidth; }
public void GetHeight() { return r. GetHeight; }
public void GetArea () { return r. GetArea; }
}
So it solves our problem.
Sunday, 1 May 2011
Cyclic inheritance in java
The compiler checks for cyclic inheritance like a class extending another class and the second class extending the first class. e.g.
Class Foo extends Bar{}
Class Bar extends Foo{}
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
cpp vs Java : Abstract classes
A class that contains at least one pure virtual function is said to be abstract. Because an abstract class contains one or more functions for which there is no definition (that is, a pure virtual function), no objects of an abstract class may be created. Instead, an abstract class constitutes an incomplete type that is used as a foundation for derived classes.
Although you cannot create objects of an abstract class, you can create pointers and references to an abstract class. This allows abstract classes to support run-time polymorphism, which relies upon base-class pointers and references to select the proper virtual function.
Using super in java
'super' is used for pointing the super class instance. In java it has following usage :
Multilevel inheritance - Calling order of constructors
// Demonstrate when constructors are called.
// Create a super class.
class A {
A() {
System.out.println("Inside A's constructor."); }
}
// Create a subclass by extending class A.
class B extends A {
B() {
System.out.println("Inside B's constructor.");
}
}
// Create another subclass by extending B.
class C extends B {
C() {
System.out.println("Inside C's constructor.");
}
}
class CallingCons {
public static void main(String args[]) {
C c = new C();
}
}
The output from this program is shown here:
Inside A’s constructor
Inside B’s constructor
Inside C’s constructor
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.
Tuesday, 1 February 2011
Composition vs Inheritance
Given that the inheritance relationship makes it hard to change the interface of a superclass, it is worth looking at an alternative approach provided by composition. It turns out that when your goal is code reuse, composition provides an approach that yields easier-to-change code.
Code reuse via inheritance
For an illustration of how inheritance compares to composition in the code reuse department, consider this very simple example:
class Fruit {
// Return int number of pieces of peel that
// resulted from the peeling activity.
public int peel() {
System.out.println("Peeling is appealing.");
return 1;
}
}
class Apple extends Fruit {
}
class Example1 {
public static void main(String[] args) {
Apple apple = new Apple();
int pieces = apple.peel();
}
}When you run the Example1 application, it will print out "Peeling is appealing.", because Apple inherits (reuses) Fruit's implementation of peel(). If at some point in the future, however, you wish to change the return value of peel() to type Peel, you will break the code for Example1. Your change to Fruit breaks Example1's code even though Example1 uses Apple directly and never explicitly mentions Fruit. Here's what that would look like:
class Peel {
private int peelCount;
public Peel(int peelCount) {
this.peelCount = peelCount;
}
public int getPeelCount() {
return peelCount;
}
//...
}
class Fruit {
// Return a Peel object that
// results from the peeling activity.
public Peel peel() {
System.out.println("Peeling is appealing.");
return new Peel(1);
}
}
// Apple still compiles and works fine
class Apple extends Fruit {
}
// This old implementation of Example1
// is broken and won't compile.
class Example1 {
public static void main(String[] args) {
Apple apple = new Apple();
int pieces = apple.peel();
}
}Code reuse via compositionComposition provides an alternative way for
Apple to reuse Fruit's implementation of peel(). Instead of extending Fruit, Apple can hold a reference to a Fruit instance and define its own peel() method that simply invokes peel() on the Fruit. Here's the code: class Fruit {
// Return int number of pieces of peel that
// resulted from the peeling activity.
public int peel() {
System.out.println("Peeling is appealing.");
return 1;
}
}
class Apple {
private Fruit fruit = new Fruit();
public int peel() {
return fruit.peel();
}
}
class Example2 {
public static void main(String[] args) {
Apple apple = new Apple();
int pieces = apple.peel();
}
}In the composition approach, the subclass becomes the "front-end class," and the superclass becomes the "back-end class." With inheritance, a subclass automatically inherits an implemenation of any non-private superclass method that it doesn't override. With composition, by contrast, the front-end class must explicitly invoke a corresponding method in the back-end class from its own implementation of the method. This explicit call is sometimes called "forwarding" or "delegating" the method invocation to the back-end object. The composition approach to code reuse provides stronger encapsulation than inheritance, because a change to a back-end class needn't break any code that relies only on the front-end class. For example, changing the return type of
Fruit's peel() method from the previous example doesn't force a change in Apple's interface and therefore needn't break Example2's code. Here's how the changed code would look:
class Peel {
private int peelCount;
public Peel(int peelCount) {
this.peelCount = peelCount;
}
public int getPeelCount() {
return peelCount;
}
//...
}
class Fruit {
// Return int number of pieces of peel that
// resulted from the peeling activity.
public Peel peel() {
System.out.println("Peeling is appealing.");
return new Peel(1);
}
}
// Apple must be changed to accomodate
// the change to Fruit
class Apple {
private Fruit fruit = new Fruit();
public int peel() {
Peel peel = fruit.peel();
return peel.getPeelCount();
}
}
// This old implementation of Example2
// still works fine.
class Example1 {
public static void main(String[] args) {
Apple apple = new Apple();
int pieces = apple.peel();
}
}This example illustrates that the ripple effect caused by changing a back-end class stops (or at least can stop) at the front-end class. Although Apple's peel() method had to be updated to accommodate the change to Fruit, Example2 required no changes. Composition vs Inheritance 2
When you establish an inheritance relationship between two classes, you get to take advantage of dynamic binding and polymorphism. Dynamic binding means the JVM will decide at runtime which method implementation to invoke based on the class of the object. Polymorphism means you can use a variable of a superclass type to hold a reference to an object whose class is the superclass or any of its subclasses.
One of the prime benefits of dynamic binding and polymorphism is that they can help make code easier to change. If you have a fragment of code that uses a variable of a superclass type, such as
Fruit, you could later create a brand new subclass, such as Banana, and the old code fragment will work without change with instances of the new subclass. If Banana overrides any of Fruit's methods that are invoked by the code fragment, dynamic binding will ensure that Banana's implementation of those methods gets executed. This will be true even though class Banana didn't exist when the code fragment was written and compiled. Thus, inheritance helps make code easier to change if the needed change involves adding a new subclass. This, however, is not the only kind of change you may need to make.
Changing the superclass interface
In an inheritance relationship, superclasses are often said to be "fragile," because one little change to a superclass can ripple out and require changes in many other places in the application's code. To be more specific, what is actually fragile about a superclass is its interface. If the superclass is well-designed, with a clean separation of interface and implementation in the object-oriented style, any changes to the superclass's implementation shouldn't ripple at all. Changes to the superclass's interface, however, can ripple out and break any code that uses the superclass or any of its subclasses. What's more, a change in the superclass interface can break the code that defines any of its subclasses.
For example, if you change the return type of a public method in class
Fruit (a part of Fruit's interface), you can break the code that invokes that method on any reference of type Fruit or any subclass of Fruit. In addition, you break the code that defines any subclass of Fruit that overrides the method. Such subclasses won't compile until you go and change the return value of the overridden method to match the changed method in superclass Fruit. Inheritance is also sometimes said to provide "weak encapsulation," because if you have code that directly uses a subclass, such as
Apple, that code can be broken by changes to a superclass, such as Fruit. One of the ways to look at inheritance is that it allows subclass code to reuse superclass code. For example, if Apple doesn't override a method defined in its superclass Fruit, Apple is in a sense reusing Fruit's implementation of the method. But Apple only "weakly encapsulates" the Fruit code it is reusing, because changes to Fruit's interface can break code that directly uses Apple. 
