Monday, October 13, 2014

Programming with interface and programming to interface

Another good habit that every programmer adopt is programming to interfaces, rather than programming to implementations. It is clearly not about using interfaces in your application, though you are using interfaces at design level, it is very hard to make coders to get benefit out it. There is a very big difference between programming with interfaces and programming to interfaces. The main difference is that
  • programming with interfaces -design level
  • programming to interfaces -coding level

To understand what I exactly mean, just look into the below example.

 interface Animal {  
   public void eat();  
 }  
 class Human implements Animal{  
   public void eat(){  
     // Eat cakes and Buns   
   }  
 }  
 class Dog implements Animal{  
   public void eat(){  
     // Eat bones   
   }  
 }  
If you see the above code, we just took an interface called Animal and designed another two classes by implementing the same interface. Let's now discuss where exactly the two sentences programming with interfaces and programming to interfaces comes into picture.

Programming with Interfaces :

Keeping the above code in mind, at design level (before start coding) itself one must decide weather to use interfaces or not based on the business logic. In the above example I decide to place an interface called Animal and I'll put all the common functionality in the interface. Later if you are saying that your class is said to be an Animal, you class must implement my Animal interface. Later I'l use that Interface to write my generic methods, and to create generic functionality. For ex, I can create methods like this
public makeAnimalEat( Animal animal ) {   
  animal.eat();   
  }  
 Dog dog = new Dog();  
 makeAnimalEat(dog);  
 //since every Dog implement interface, it is allowed to pass Dog to that method.
Another method to make a group eat,
public static makeAllAnimalsEat( List<Animal> animals ) {  
  for (Animal animal : animals) {  
  animal.eat();  
 } 
In above methods (instance or static methods) though you are not aware of what type of animal being passed to the method, you can still make the Animal eat. The above shown methods are just small examples and like wise you can create much more complex functionality with simple effort of making/planning your functionality with Interfaces. This is exactly programming with interfaces. When ever there is a possibility, go ahead and use Interface instead a Class so you won't end up in writing different methods for different Classes.


Programming to Interfaces :

The concept of programming to interface comes in to picture only at the time of creating/instancing of object. Consider you are writing code to create Room in Zoo. Each room have an Animal inside it. Let's call it as a DogRoom.
public class AnimalRoom {  
 // creating an animal inside Room  
 Dog dog = new Dog();  
 dog.doSomeThing();  
 // play with dog  
 } 
The above code works fine and you need not worry about it. Problem arises when you planning to change the type of Animal inside the room. For example you are planning to change to a Cat. Then if you are writing Dog dog = new Dog() and when you want to change it to Cat , you have to check/change all the methods/variables of Dog to Cat. But if you program to interface 
Animal animal = new Dog();  
// play with animal here  
When ever you need to change just change the Right Hand Side of the initialization part and you are done without any code breakage and without any compiler error.
Animal animal = new Cat();  
// play with animal here 
You are just done. Nothing to change other than that initialization part. That is what exactly programming to interface.

Wednesday, October 8, 2014

NoSuchMethodException vs NoSuchMethodError in Java

As we all know that there is a clear difference between Exception and Error. You can recover from an Exception but cannot from an Error. That's the basic difference. Coming to our actual problem which related to NoSuchMethod, we have NoSuchMethodException and NoSuchMethodException. Let us see, when and why occurs what.

NoSuchMethodException:


This exception occurs when you try to access a method which is not present in the class. Consider there is a Class called Consumer. And Consumer calling a method called sellMe() of Class Buyer which is not actually presented in Buyer class. If you are calling normally invoking this, an compile time occurs, Normally in the sense without using reflection .

If you are using reflection and trying to invoke a method using reflection like below, there are chances to get NoSuchMethodException, if your Buyer class doesn't have sellMe() method. 
Class b = Class.forName("java.blog.Buyer");  
           try {  
                Method m = b.getDeclaredMethod("sellMe", params);  
           } catch (NoSuchMethodException e) {  
                e.printStackTrace();  
           }  
Since that is a Exception you can simply catch it and can proceed with your flow, where as it is not possible with NoSuchMethodError.

NoSuchMethodError:


This error occurs when there is a method missing at run time from the other class where the method actually there while you are compiling. Confused ? Let see with an example. 

Consider you have 2 classes, Consumer and Buyer. From Consumer you called a method of Buyer using it's instance. Later you removed the method from Buyer and compile the Buyer alone. So now Consumer messed up right?, which is still trying to refer the method sellMe(). Yes it is.

You just the changed/removed a method of Buyer , where the Consumer don't know about this change and still using the same. Hence the Error arises. Usually we run into this error in cases like we are using a third party library or jar that depends on another jar. Where the first jar invoking a method in second second jar which is not at all present because of incompatible versions. Keeping the compatible versions of jar's removes the error.

Tuesday, September 23, 2014

IOException : tmpFile renameTo classFile failed in JSP.

When I run the Jsp suddenly ran in to the below exception.
HTTP ERROR: 500  
 tmpFile.renameTo(classFile) failed  
 RequestURI=/Index.jsp  
 Caused by:  
 java.io.IOException: tmpFile.renameTo(classFile) failed  
  at org.apache.jasper.compiler.SmapUtil$SDEInstaller.install(SmapUtil.java:241)  
  at org.apache.jasper.compiler.SmapUtil.installSmap(SmapUtil.java:163)  
  at org.apache.jasper.compiler.Compiler.generateClass(Compiler.java:429)  
  at org.apache.jasper.compiler.Compiler.compile(Compiler.java:472)  
  at org.apache.jasper.compiler.Compiler.compile(Compiler.java:451)  
  at org.apache.jasper.compiler.Compiler.compile(Compiler.java:439)  
  at org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:511)  
  at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:295)  
  at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:292)  
  at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:236)  
  at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)  
  at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:487)  
  at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:362)  
  at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)  
  at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:181)  
  at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:729)  
  at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:405)  
  at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)  
  at org.mortbay.jetty.handler.RequestLogHandler.handle(RequestLogHandler.java:49)  
  at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)  
  at org.mortbay.jetty.Server.handle(Server.java:324)  
  at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:505)  
  at org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:829)  
  at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:513)  
  at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:211)  
  at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:380)  
  at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:395)  
  at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:488)  
 Powered by Jetty://  

Cause of problem:


This happens when you have temporary class file generated for JSP and when you are restarting or reloading the Jsp, the same class file will be overridden with new content (name as well may be). When ever there is a problem in between doing this, this exception throws on our face :).

Resolution :


After so many restarts of my app and even PC too, I found the below solution.

  • Stop your application.
  • Clear you temp folder in the System.
  • Clean the project.
  • Restart the application.

Hope that solves your problem. Cheers.

Friday, September 19, 2014

Constructor inheritance(ovveriding) and reasons behind restricting constructor inheritance in Java.

Inheritance is one the key concept of OOP. Being object oriented language, Java supports it. With inheritance every Child becomes a Parent. You can access the properties of Parent from a Child once you inherit Parent (using extends keyword). Here is a key point to note that, though you can access the members of Parent you cannot inherit/ or override constructor in Java. In this article let us discuss the reasons behind restricting Constructor Inheritance.
  • With inheritance you can access only Class members from Parent. Since constructor is not a class member, hence you cannot inherit from Parent. In a class, class members are only Fields, Methods and Nested classes.
  • Another possible reason to restrict constructor inheritance is that as we discussed in the article about constructor constructor must be the Class's simple name. If you inherit your parent constructor, then the rule breaks as Child and Parent have a different Class names.
  • And also consider Parent class have a no argument constructor and when you inherit that Parent, in case of Child you cannot provide Child's own default constructor which with a private access modifier. So making your Child class constructor private (downgrading the access) is a dream if there is constructor inheritance.

By observing the above points, it makes sense that there are good amount of reasons to stop overriding/inheriting the constructor of Parent. So we can conclude that the constructor inheritance is not possible in Java. That is not finishes the story. Still you can use or invoke the super class constructor.

Invoking super class constructor :

Though you cannot use inheritance with constructor are free to invoke Parent class constructor with help of super keyword from Child
(super(), super(args)).

If we are saying constructor inheritance is not possible, that doesn't mean that you cannot communicate between parent class constructor and child constructors. There can be a clean communication between the constructors using super keyword.
ChildClassConstructor(){  
   super(param_needed); //Invoking super class constructor with params  
 }  
 ChildClassConstructor(){  
   super(); //Invoking super class default constructor.  
 }  
Like the way shown in above you can invoke any super class constructor using super. That is all about invoking Parent class constructor and what happens when you are not explicitly invoking any super class constructor (for your needs)?? Though you are not invoking Invoking a super class constructor doesn't mean that you are executing only Child class constructor alone. There is a interesting fact that your super class constructors(till n'th super class, which is Object class constructor) also calls in that process(shown below in code). you can observe when you invoke any Child constructorThere is a chain call to the immediate parent class constructor from the current class. And the call continues until the Object class constructor invokes since that the possible most Parent classes super class is. For ex:
 public class ParentClass {  
      public ParentClass() {  
           System.out.println("Parent default constructor invoked");  
      }  
      public ParentClass(int a) {  
           System.out.println("Parent argumented constructor invoked");  
      }  
      public static void main(String[] args) {  
           SubSubClass sub = new SubSubClass();  
      }  
 }  
 class SubClass extends ParentClass {  
      public SubClass() {// not calling any super  
           System.out.println("Child default constructor invoked");  
      }  
      public SubClass(int b) {  
           super(b);  
           System.out.println("Child default constructor invoked");  
      }  
 }  
 class SubSubClass extends SubClass {  
      public SubSubClass() {// not calling any super  
           System.out.println("Sub Child default constructor invoked");  
      }  
      public SubSubClass(int b) {  
           super(b);  
           System.out.println("Sub Child default constructor invoked");  
      }  
 }  
 OUTPUT:  
 Parent default constructor invoked  
 Child default constructor invoked  
 Sub Child default constructor invoked

As you are seeing that we are not calling any super class constructor, still we can see the calling hierarchy of Constructor calling till the most possible super class which Object class's constructor and returns to the current (Child) class's constructor business logic. Summarizing the points to remember below.
  • If you call any specific super constructor (super or super(args)), then that specific super constructor invokes.
  • If you are not calling any specific constructor, then default super constructor(super()) invokes.
  • When you invoke any specific (super(args)) parent constructor that only executes and default constructor of Parent wont get execute.

Constructor overloading and constructor chaining in Java

Whenever people just say constructor is just like a method, I'm really scared about their understanding and I really pity on constructor. The concept of constructor is completely different from a normal method. When we actually want to dig in to the core concepts, one of the key point to learn is about constructor which is used to initialize the class properties (or any other initial business logic after initialization of properties) while object creation.

What exactly we have to say is it looks like just a method but which is entirely a different thing and lot of things happen under the hood when you invoke constructor. To create an instance we must need a constructor for every Java Class. A good point to remember here is, a constructor never return anything.
JavaConstructor jCInstance = new JavaConstructor(); 
If you see the above line of code JavaConstructor is the class name and JavaConstructor() is the constructor of it. 
class JavaConstructor{  
   JavaConstructor() {   //default or no argument constructor
   //do something   
   }  
 }  
To be valid the class declaration of JavaConstructor must be the simple name of the class. Here in the above declaration I left the access modifier as default for the constructor.

 Argumented Constructor:-

An argumented constructor is which used to pass required information to the class while creating an object. Below example demonstrates that how Bus class is forcing the consumers to pass the number of seats  while creating a Bus.
Class Bus{   
  int seats;  
   Bus(int seats) {  // argumented constructor  
   this.seats = seats;  
   //do something    
   }   
  }  
Now whom so ever want to create a Bus, they can pass the no.of seats required to the Bus class. Just for example I took seats. Depends on the requirement's the arguments list may vary(color,length etc ..).
Bus volvoBus = new Bus(34); //passing seat count
Bus ordinaryBus = new Bus(28); //passing seat count

The points to note here are
  • If you forgot to write or not intentionally writing a constructor to your class, JVM creates a one for you internallywhich is a default no argument constructor.
  • If you provide a default (no arg) constructor, JVM uses it to instantiate.
  • If you are not providing default constructor and providing a argumented constructor, then consumers definitely needs to pass the required parameters. In this case, consumers cannot use default constructor anymore since you provided a argumented one and not providing default on while creating object. If they try to use default one compiler error occurs. 
Constructor Overloading:-

Just like method overloading in Java, there is constructor overloading too. Overloading a constructor means providing multiple constructors differing in arguments for a Class. For ex:
public class Bus {  
      int noOfSeats;  
      String busColor;  
      public Bus() {  
           System.out.println("This is default constructor");  
      }  
      public Bus(int seats) {  
         this.noOfSeats = seats;  
           System.out.println("To call this constructor, you need need to pass no of seats");  
      }  
      public Bus(int seats, String color) {  
         this.noOfSeats = seats;  
         this.busColor = color;  
           System.out.println("To call this constructor, you need to pass bus color");  
      }  
 }  
If you see there are multiple constructors provided with different arguments. We just overloaded the constructor. When we want to create a required bus we have to just use the appropriate constructor. It's up to us to create/passing info while creating a bus. You may buy a bus with 20 seats and color it later. Creating different types of buses is possible with above provided constructors.
class BusCreator {  
      public static void main(String[] args) {  
           Bus bus = new Bus();// I just need a bus'  
           Bus seatsBus = new Bus(20);// I need a bus with 20 seats  
           Bus coloredBus = new Bus(25, "Blue");// Need a blue color bus with 20 seats.  
      }  
 }  

Constructor Chaining-

Like the confusion between method and constructor, few usually state that invoking Parent class constructor from Child is constructor chaining. No. That is not 100% true. Weather it is own constructor or Parent constructor, invoking one constructor from other can state as constructor chaining. Lets see the below examples how usually chaining the constructor happens with in the same class and with Parent class.


We chain(calling) one constructor from other with in the same classso that we can avoid code duplication. Without chaining every constructor have whole business logic and that leads to code duplication and hard to maintain the code as well.
public class Bus {  
      int noOfSeats;  
      String busColor;  
      public Bus() {  
           constructBus();  
      }  
      public Bus(int seats) {  
           this();// calling default constructor for business logic.  
           this.noOfSeats = seats;  
      }  
      public Bus(int seats, String color) {  
           this(seats); // Using another constructor and proceeding..  
           this.busColor = color;  
      }  
      private void constructBus() {  
           // Whole process of constructing bus.  
      }  
 }  
Below we chained Parent constructor to Child constructor as below to pass the required information to Parent while creating a Child object.
public class Vehicle {  
      private String vehicleName;  
      public Vehicle(String name) {  
           this.vehicleName = name;  
      }  
 }  
 class Bus extends Vehicle {  
      int noOfSeats;  
      String busColor;  
      public Bus() {  
           super("bus"); // calling super constructor.  
           constructBus();  
      }  
 }