Showing posts with label inheritance. Show all posts
Showing posts with label inheritance. Show all posts

Tuesday, July 5, 2011

Mapping Entities with Inheritance

Again there are a number of ways Hibernate can handle inheritance. These are based on the standard techniques for reducing generalisation hierarchies in entity-relationship diagrams.

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, June 24, 2011

Compiling cyclic dependency in Java

I recently cam across– If there is cyclic dependency between classes A, B and C. How do you go about compiling them in java? Apparently, that came up in an interview for someone.
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.

Sunday, June 12, 2011

Various relations in software design - Association, Aggregation, Composition, Abstraction, Generalization, Realization, Dependency

We will just discuss about some of the terms used in software engineering, regarding relationship among the objects, and how they are represented in class diagram.

Association

Association is a relationship between two objects. In other words, association defines the multiplicity between objects. You may be aware of one-to-one, one-to-many, many-to-one, many-to-many all these words define an association between objects. Aggregation is a special form of association. Composition is a special form of aggregation.

Example: A Student and a Faculty are having an association. The relationship between a car and a driver is representative of this relationship. The car will have a driver who will be associated with the car for a period of time.

Aggregation

Aggregation is a special case of association. A directional association between objects. When an object ‘has-a’ another object, then you have got an aggregation between them. Direction between them specified which object contains the other object. Aggregation is also called a “Has-a” relationship.

 
A FileReader object that has been created using a File object represents a mutual dependency where the two objects combine to create a useful mechanism for reading characters from a file. The UML symbols for expressing this relationship as shown in following figure which involve a line connecting the two classes with a diamond at the object that represents the greater whole.


Composition

Composition is a special case of aggregation. In a more specific manner, a restricted aggregation is called composition. When an object contains the other object, if the contained object cannot exist without the existence of container object, then it is called composition.

Example: A class contains students. A student cannot exist without a class. There exists composition between class and students. Other example of this is a customer object and its related address object; the address object cannot exist without a customer object. This relationship is shown with a darkened diamond at the object, which represents the greater whole, as shown in the following figure:

Difference between aggregation and composition

Composition is more restrictive. When there is a composition between two objects, the composed object cannot exist without the other object. This restriction is not there in aggregation. Though one object can contain the other object, there is no condition that the composed object must exist. The existence of the composed object is entirely optional. In both aggregation and composition, direction is must. The direction specifies, which object contains the other object.
Example: A Library contains students and books. Relationship between library and student is aggregation. Relationship between library and book is composition. A student can exist without a library and therefore it is aggregation. A book cannot exist without a library and therefore its a composition. For easy understanding I am picking this example. Don’t go deeper into example and justify relationships!

Abstraction

Abstraction is specifying the framework and hiding the implementation level information. Concreteness will be built on top of the abstraction. It gives you a blueprint to follow to while implementing the details. Abstraction reduces the complexity by hiding low level details.
Example: A wire frame model of a car.

Generalization

Generalization uses a “is-a” relationship from a specialization to the generalization class. Common structure and behaviour are used from the specializtion to the generalized class. At a very broader level you can understand this as inheritance. Why I take the term inheritance is, you can relate this term very well. Generalization is also called a “Is-a” relationship.

Example: Consider there exists a class named Person. A student is a person. A faculty is a person. Therefore here the relationship between student and person, similarly faculty and person is generalization.

Realization

Realization is a relationship between the blueprint class and the object containing its respective implementation level details. This object is said to realize the blueprint class. In other words, you can understand this as the relationship between the interface and the implementing class.

Example: A particular model of a car ‘GTB Fiorano’ that implements the blueprint of a car realizes the abstraction.

Dependency

Change in structure or behaviour of a class affects the other related class, then there is a dependency between those two classes. It need not be the same vice-versa. When one class contains the other class it this happens.

Example: Relationship between shape and circle is dependency. The same relationship would exist for a stock transfer object that needed to use a stock item object to get the information on the stock item being transferred. The stock transfer object would have a dependency relationship with the stock item object; the stock transfer object would read the transfer information and could then discard the stock item object and continue processing.

How to force the subclasses of a concrete class to override a method?

There is no such real world scenario where a concrete entity will want to force a more specific entity to override its method. If it is to be overridden then why not make the super class as abstract.

Anyways, the logic behind the interview questions being asked now a days is something which requires best talent from the psychology field.

Solution: The solution which I have come up with for the above Java Interview question is to use the instanceof operator in the super class and throw an exception if the instance on which method is being invoked is found to be of the sub class. The sample program showing this scenario follows:

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, May 24, 2011

Solution to Square rectangle problem

We have already gone through this problem here.
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.

The Square and Rectangle problem OR Circle and Eclipse Problem

Most people would think that a Square is a special kind of Rectangle and therefor intuitively inherit their Square class from the Rectangle class to be able to reuse code. Similar way goes for Circle and eclipse, where circle is considered eclipse's extension and special case.


Notice that the Rectangle have a couple of traits that the Square does NOT and vice versa. First of all the Square has only *ONE* attribute; size, while the Rectangle have *TWO* attributes; width & height. And this fact may for some problems be quite tricky to discover sometimes. And if you do the capital sin of inheriting your Square class from your Rectangle class, then you might currently get around it by hiding the width property of the Rectangle somehow, maybe by convention, and then just let the size property of the Square forward the call to height or something similar, but this is always wrong!

So consider the rectangle class:
public class Rectangle   
{  
    private double width;  
    private double height;  
    public void SetWidth (double w) { width = w; }  
    public void SetHeight (double h) { height = h; }  
    public void GetWidth () { return w; }  
    public void GetHeight () { return h; }  
    public void GetArea () { return width * height; }  
}

Consider the square class:
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; }  
}

But Square has to somehow guarantee that its width and height are same or in other words height is redundant. So if client changes height, it has to change width accordingly.
Why is it that the client code gets affected by the derived class object reference being given in place of a base class object reference? Because the derived class's post-condition is weaker than that of the base class. The base class promises that if you call the SetHeight function, it will change the value of the height, but will do nothing to the value of width. But nothing like that happens in derived class and therefore, a client who is relying on the above base class gets affected when it gets a derived class object reference instead.

Therefore, inheritance is not the right approach in this situation. Delegation is the right choice. See here for solution to this problem.

Friday, May 20, 2011

Open Close Principle ( OCP )

The Open-Closed Principle lies at the heart of the object-oriented paradigm. In a sense, we can say that its the goal of our object-oriented designs. Examining a myriad of patterns reveals its application often. It states the following:
Software entities should be open for extension, but closed for modification.

So it has 2 attributes:
  1. Open For Extension - It is possible to extend the behavior of the module as the requirements of the application change (i.e. change the behavior of the module).So classes can be extended
  2. Closed For Modification - Extending the behavior of the module does not result in the changing of the source code or binary code of the module itself.

Example - Violation of OCP
Consider the classes hierarchy:

class Animal
{
     protected String sound;
}

class Cat extends Animal
{
      //getters and setters
}

class Dog extends Animal
{
    //getters and setters
}

Now consider the class, which manages the animals and make them sound.
SoundManager.java
public class SoundManager{
    private List<Animal> animalList;
        
    public SoundManager(){
        animalList = new ArrayList<Animal>();
    }

    public void add(Animal a){
        animalList.add(a);
    }
    public void makeSound(){
        for(Animal a : animalList)
            if(a instanceof Cat)
                makeMew(a);
            else if(a instanceof Dog)
                makeBark(a);
    }
    public void makeMew(Animal a){
        print(a.getSound());
    }
    public void makeBark(Animal a){
        print(a.getSound());
    }

}
Note that this is not a good solution because suppose a new class Lion comes into picture, and it has a sound called roar, you have to edit the code and another if else or switch() to make that work. So it is violation of OCP.

Solution
So a good solution would be to make makeSound function part of class hierarchy itself.

class Animal
{
     protected String sound;
     public abstract void makeSound();  
}

class Cat extends Animal
{
      //getters and setters
     @Override
     public void makeSound(){
          print("mew");
     }
}

class Dog extends Animal
{
    //getters and setters
     @Override
     public void makeSound(){
          print("bark");
     }
}

Now it is much robust to write the above code, no matter how many animals you add.
public class SoundManager{
    private List<Animal> animalList;
        
    public SoundManager(){
        animalList = new ArrayList<Animal>();
    }

    public void add(Animal a){
        animalList.add(a);
    }
    public void makeSound(){
        for(Animal a : animalList)
            a.makeSound();
    }
    //makeBark, makeMew() functionr removed

}

Note of caution
It sems from the 80s and 90s when OO frameworks were built on the principle that everything must inherit from something else and that everything should be subclassable. So for example take a class called Stack in java, it subclasses Vector. So why on earth will you need push and pop if you can directly access element's index?
Joshua Bloch in his famous book "Effective Java" gives the following advice: "Design and document for inheritance, or else prohibit it", and encourages programmers to use the "final" modifier to prohibit subclassing.
So keep in mind, use inheritance only when its compulsory, otherwise try to make your classes final if you feel in future you won't be extending them.

Summary
It should be clear that no significant program can be 100% closed. So we may need to change the code depending on the requirement, but we can try to make our code as robust as possible. Though it comes with experience.

Sunday, May 1, 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{}

results in compiler error.

Abstract Classes Have Constructors in decompiled code

1) In Java , we have default constructors provided for classes by the compiler (in case one is not declared).

2) The abstract classes can't be instantiated by using the new operator because they don't provide full implementation of all the methods.

Then does it make sense to have constructors inside abstract classes. Let us find it using a sample abstract class:
public abstract class Test{
   public abstract void doSomething();
}

The decompiled code for this class will show the truth about constructors in abstract classes in Java
public abstract class Test
{
    public Test()
    {
    }
    public abstract void doSomething();
}


Why?

The reason is that when a class extends any other class and an instance of the subclass is created then the constructor calls are chained and the super class constructors are invoked. This rule is no exception for abstract class

Moreover, having constructors in a class doesn't necessarily mean that instance of that class will be created using the new operator, but the constructors are intended for writing any initializing code.

Saturday, April 23, 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

cpp vs Java : Abstract classes

CPP :
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 :

 

Inheritance : c++ vs java

Inheritance is similar in Java and C++. Java uses the extends keyword instead of the : token. All inheritance in Java is public inheritance; there is no analog to the C++ features of private and protected inheritance.

Multilevel inheritance - Calling order of constructors

In case of multilevel of inheritance , Base class constructor is called 1st.

// 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


Monday, April 18, 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.


Sunday, April 17, 2011

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, March 31, 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.

Saturday, March 19, 2011

Spring : Inheritance between beans

Its obvious that inheritance help us reuse common behaviour across. From spring perspective, those beans which share common set of dependencies, will share a common base class.

Example : All repository classes require a DataSource, so instead of declaring the datasource again and again, we can have a base class containing the DataSource.

Consider the following classes :

Let us define a base class :

import javax.sql.DataSource;

public abstract class BaseRepository {

private DataSource dataSource;

public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}

public DataSource getDataSource() {
return dataSource;
}

}


Now suppose one class just extends it :


public class FlightRepositoryImpl extends BaseRepository implements FlightRepository {


Now for spring handling this dependency we use 2 attributes : abstract and parent


<import resource="db-config.xml" />

<!-- set the parent/child relationship by abstract -->
<bean id="baseRepo" class="common.BaseRepository" abstract="true">
<property name="dataSource" ref="ds" />
</bean>

<!-- set the parent/child relationship by refering to the parent bean -->
<bean id="flightRepo" class="com.XXX.FlightRepositoryImpl" parent="baseRepo" />

Monday, February 21, 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.

Chitika