Speed up your build with Maven 3

I have been trying to find ways to make my project’s maven build run fast. It is very frustrating and annoying when your project’s full build takes 12 minutes to complete. It does not happen too often in a day because you work at module level,  but 2-3 times a day you need to build the full project and if your build takes this long,  it really slows you down. These days builds take a lot of time because you embed all sorts of plugins in your build like checkstyle, findbugs, cobertura (It is evil because it run your test twice), etc.  Although,  It does give you time to have coffee but 12 minutes is way too much. So, I was really pissed off.

Few days back I was checking my tweets and found out that Maven is releasing its new version and it will have some performance improvements. Maven 3 is the latest version of maven which is expected to be released today.  So, I decided to play with it. I downloaded the beta version of  Maven 3, changed my windows path system variable to point to Maven 3 and ran a mvn clean install on my project. Without any build failures or other problems, the build just ran fine. I have heard that when Maven 2 was released people had hard time migrating from version 1 to 2 as it was not backward compatible. But Maven 3.0 is completely backward compatible and most of the plugins will also work fine. To my surprise, the build took 9 minutes. This is still a high number but it was way better than 12 minutes. Seeing this decrease in build time motivated me to read more about Maven 3.

After reading some blogs and watching Jason Van Zyl presentation,  I found out that there are lot of new features in Maven 3. One of the new features in Maven3 is Parallel Builds. Parallel build analyzes your project’s dependency graph and schedule modules that can be run in parallel. This is a very cool feature and it really sped up the build. To run a paralled build, you can type

mvn -T 4 clean install
mvn -T 2C clean install

The first command will run your build with 4 threads and second command will build your project with 2 threads per core. How fast your build will become, depends a lot on your project/build structure, how your unit tests are distributed in modules  so it may vary from project to project. For my project with 4 threads, the build time got reduced to under 6 minutes, which I think is  great.  You should try out some combination with number of threads or number of threads per core to find out the best possible combination for your project. I am very happy that build time of my project got reduced to almost half.

In his presentation, Jason Van Zyl talks a shell based tool called Maven Shell which can also further improve the performance. Maven Shell is maven embedded in a long lived shell process. It does not comes bundled with maven 3 so you have to download it from http://shell.sonatype.org/. I tried running my project build inside Maven Shell but it gives PermGen space error all the time. I tried changing the perm gen memory setting but it didn’t helped. Maven shell is expected to run much fast because it caches the parsed POMs.

Maven 3 is definitely worth spending time so have a look at it. I have just touched the tip of iceberg , there are lot of new features in Maven 3.  I will try and talk about others in my future blogs.

Creating Application using Spring Roo and Deploying on Google App Engine

Spring Roo is an Rapid Application Development tool which helps you in rapidly building spring based enterprise applications in the Java programming language. Google App Engine is a Cloud Computing Technology which lets you run your application on Google’s infrastructure. Using Spring Roo, you can develop applications which can be deployed on Google App Engine. In this tutorial, we will develop a simple application which can run on Google App Engine.
Read more

Pragmatic look at Method Injection

Intent

Method injection lets container inject methods instead of objects  and provides dynamic sub classing.

Also Known As

Method decoration (or AOP injection)

Motivation

Sometimes it happens that we need to have a factory method in our class which creates a new object each time we access the class. For example, we might have a RequestProcessor which has a method called process which takes a request as an input and returns a response as an output. Before the response is generated, request has to be validated and then passed to a service class which will process the request and returns the response.As can be seen in the code below we are creating a new ValidatorImpl instance each time process method is called. RequestProcessor requires a new instance each time because Validator might have some state which should be different for each request.

public class RequestProcessor implements Processor {

	private Service service;

	public Response process(Request request) {
		Validator validator = getNewValidatorInstance();
		List<String> errorMessages = validator.validate(request);
		if (!errorMessages.isEmpty()) {
			throw new RuntimeException("Validation Error");
		}
		Response response = service.makeServiceCall(request);
		return response;
	}

	protected ValidatorImpl getNewValidatorInstance() {
		return new ValidatorImpl();
	}

}

RequestProcessor bean is managed by dependency injection container like spring where as Validator is being instantiated within the RequestProcessor. This solution looks like ideal but it has few shortcomings :-

  1. RequestProcessor is tightly coupled to the Validator implementation details.
  2. If  Validator had any constructor dependencies, then RequestProcessor need to know them also. For example, if Validator has a dependency on some Helper class which is injected in Validator constructor then RequestProcessor needs to do know about helper also.

There is also another approach that you can take in which container will manage the Validator bean(prototype) and you can make bean aware of the container by implementing ApplicationContextAware interface.

public class RequestProcessor implements Processor,ApplicationContextAware {

	private Service service;
	private ApplicationContext applicationContext;

	public Response process(Request request) {
		Validator validator = getNewValidatorInstance();
		List<String> errorMessages = validator.validate(request);
		if (!errorMessages.isEmpty()) {
			throw new RuntimeException("Validation Error");
		}
		Response response = getService().makeServiceCall(request);
		return response;
	}

	protected Validator getNewValidatorInstance() {
		return (Validator)applicationContext.getBean("validator");
	}

	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		this.applicationContext = applicationContext;
	}

	public void setService(Service service) {
		this.service = service;
	}

	public Service getService() {
		return service;
	}

}

This approach also has its drawback as the application business logic is now coupled with Spring framework.
Method injection provides a better way to handle such cases.Method injection is an injection type in which methods are injected instead of objects. The key to Method injection is that the method can be overridden to return the another bean in the container.In Spring method injection uses CGLIB library to dynamically override a class.

Applicability

Use Method injection when

  • you want to avoid container dependency as we have seen in the second approach, in which you have to inject a non singleton bean inside a singleton bean.
  • you want to avoid subclassing. For example, suppose that RequestProcessor is processing two types of response and depending upon the the type of report , we use different validators. So, we can have subclass RequestProcessor and have Report1RequestProcessor which just provides the Validator required for Report1.
  • public class Report1RequestProcessor extends RequestProcessor {
    
    	@Override
    	protected Validator getNewValidatorInstance() {
    		return new ValidatorImpl();
    	}
    
    }
    
    public abstract class RequestProcessor implements Processor {
    
    	private Service service;
    
    	public Response process(Request request) {
    		Validator validator = getNewValidatorInstance();
    		List<String> errorMessages = validator.validate(request);
    		if (!errorMessages.isEmpty()) {
    			throw new RuntimeException("Validation Error");
    		}
    		Response response = getService().makeServiceCall(request);
    		return response;
    	}
    
    	protected abstract Validator getNewValidatorInstance();
    
    	public void setService(Service service) {
    		this.service = service;
    	}
    
    	public Service getService() {
    		return service;
    	}
    
    }
    

Implementation

Method injection provides a cleaner solution. Dependency Injection container like Spring will override getNewValidatorInstance() method and your business code will be independent of both the spring framework infrastructure code as well as Concrete implementation of Validator interface. So, you can code to interface.

public abstract class RequestProcessor implements Processor {

	private Service service;

	public Response process(Request request) {
		Validator validator = getNewValidatorInstance();
		List<String> errorMessages = validator.validate(request);
		if (!errorMessages.isEmpty()) {
			throw new RuntimeException("Validation Error");
		}
		Response response = getService().makeServiceCall(request);
		return response;
	}

	protected abstract Validator getNewValidatorInstance();

	public void setService(Service service) {
		this.service = service;
	}

	public Service getService() {
		return service;
	}

}

The method requires a following signature

<public|protected> [abstract] <return-type> methodName(no-arguments);

If the class does not provide implementation as in our class RequestProcessor, Spring dynamically generates a subclass which
implements the method otherwise it overrides the method. application-context.xml will look like this

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

	<bean id="service" class="com.shekhar.methodinjection.ExampleService" />

	<bean id="requestProcessor" class="com.shekhar.methodinjection.RequestProcessor">
		<property name="service" ref="service"></property>
		<lookup-method bean="validator" name="getNewValidatorInstance"/>
	</bean>

	<bean id="validator" class="com.shekhar.methodinjection.ValidatorImpl" scope="prototype">
	</bean>
</beans>

This is how method injection can be used in our applications.

Consequences

Method injection has following benefits:
1) Provides dynamic subclassing
2) Getting rid of container infrastructure code in scenarios where Singleton bean needs to have non singleton or prototype bean.

Method injection has following Liabilities :
1) Unit testing – Unit testing will become difficult as we have to test the abstract class. You can avoid this by making the method which provides you the instance as non-abstract but that method implementation will be redundant as container will always override it.
2) Adds magic in your code – Anyone not familiar with method injection will have hard time finding out how the code is working. So, it might make your code hard to understand.

Hope this helps you understand Method Injection. It is useful in specific cases as covered in this article.

Applying Design Patterns with Java Enums

Over the weekend I was reading about Enum – a Java 5 feature which we normally use to define a set of constants like Month

public enum Month {

    JANUARY(1), FEBRUARY(2), MARCH(3), APRIL(4), MAY(5), JUNE(6), JULY(7), AUGUST(8), SEPTEMBER(9),OCTOBER(10),NOVEMBER(11),DECEMBER(12);

    private int monthIndex;

    private Month(int monthIndex) {
        this.monthIndex = monthIndex;
    }

    public int getMonthIndex() {
        return this.monthIndex;
    }
}

While reading about enums I was thinking that when enums have all the capabilities to be like a class then why we only use enums for defining constants. Most of the time we don’t even add any new method to the enum and we just use the default methods provided in an enum. Enum have default methods like name(),ordinal(), valueOf() etc because every enum extends a class called java.lang.Enum which has these methods.

In this blog, I will discuss how different design patterns can be used with enum.

Using enum for implementing Singleton – A Singleton ensures that a class has only one instance, and provide global point of access to it. Normally we create a singleton by making the constructor private and then exposing the instance either through static final member or exposing it through a static method like getInstance(). I will take an example of factory like SessionFactory because factories are mostly implemented as Singleton because an application typically needs one instance of a SessionFactory.

public class SessionFactory {

    public static final SessionFactory SESSION_FACTORY = new SessionFactory();

    private SessionFactory() {

    }

    public void doSomething() {
        System.out.println("I am doing something");
    }

}
  
public class SessionFactory {

    private static final SessionFactory SESSION_FACTORY = new SessionFactory();

    private SessionFactory() {

    }

    public static SessionFactory getInstance(){
        return SESSION_FACTORY;
    }

    public void doSomething() {
        System.out.println("I am doing something");
    }

}

The above two approaches to create singleton can broke if your SessionFactory class is Serializable, as it is not sufficient merely to add implements Serializable to its declaration. Each time a serialized instance is deserialized, a new instance of SessionFactory will be created. In order to avoid this, you should declare all instance fields transient and provide a readResolve method (readResolve method allows a class to replace/resolve the object read from the stream before it is returned to the caller ) .

private Object readResolve() {
        return SESSION_FACTORY;
    }

From Java 5 onwards, there is a new approach for implementing Singleton i.e. using enums.

public enum SessionFactory {

    SESSION_FACTORY;

    public void doSomething() {
        System.out.println("I am doing something");
    }
}

Using this approach, you don’t have to worry about serialization problems as enums (are serializable by default) handles it for you. This approach is more cleaner and is considered to be the best way to implement a singleton. Use this approach next time you need to implement a singleton.

Using enums for strategies : The Gang of Four definition of Strategy pattern is ” Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it”. Suppose, we are adding Validation logic in our application and you have different validation rules which can be applied. So, we can have one interface called ValidationRule interface (which defines different validation rules or strategies)

interface ValidationRule {
   void validate(input,result);
}

and then we define two validation rule strategies called Rule1 and Rule 2 which implements ValidationRule interface.

class Rule1 implements ValidationRule{
   public void validate(input,result){
    [business logic here .....];
   }
}

class Rule2 implements ValidationRule{
   public void validate(input,result){
     [business logic here .....];
   }
}

Then we inject a list of ValidationRule strategies into a Validator class using spring dependency injection.

class Validator {
ValidationResult result;
List<ValidationRule> rules;

    public void setRules(List<ValidationRule> rules){
     this.rules=rules;
    }
    public ValidationResult validate(input){
       for(ValidationRule rule:rules){
         rule.validate(input,this.result);
    }
 }
}

<bean id="validator">
 <property name="rules">
   <list>
     <bean class="com.shekhar.business.rules.Rule1"/>
     <bean class="com.shekhar.business.rules.Rule2"/>
   </list>
 </property>
</bean>

This was one way of using strategies with normal Java classes and interfaces.

In the second approach, Instead of making Rule1 and Rule2 as classes we can make them as enums.

enum Rule1 implements ValidationRule {

    Rule1;

    public void validate(input,result) {
      // business logic
    }
}

enum Rule2 implements ValidationRule {

    Rule2;

    public void validate(input,result) {
      // business logic
    }
}

You can also inject the enums using spring like this.

<bean name="validator" class="test.Validator">
		<property name="rules">
			<list>
				<ref bean="rule1"/>
				<ref bean="rule2"/>
			</list>
		</property>
	</bean>

	<bean id="rule1" class="test.Rule1" factory-method="valueOf">
		<constructor-arg>
			<value>RULE1</value>
		</constructor-arg>
	</bean>

	<bean id="rule2" class="test.Rule2" factory-method="valueOf">
		<constructor-arg>
			<value>RULE2</value>
		</constructor-arg>
	</bean>

The enum bean created by spring will always be a singleton whether you define a bean as singleton or prototype because enums are singleton.
The enum strategies approach can have advantage over the class strategies approach if you want to persist the strategies into the database using an ORM like hibernate that has support for java enum.

Using enum with template methods : The enum Rule1 and Rule2 can be moved to a single enum called ValidationRules which will define a template method called validate which all the defined set of instance will implement.

public enum ValidationRules {

    RULE1(){
      @Override
        public void validate() {

        }
    },
    RULE2(){
      @Override
        public void validate() {

        }
    };

    // template method
    public abstract void validate();

}

As you can see we have defined a template method called validate and both the instances RULE1 and RULE2 are providing an implementation of this method.

New Java Puzzler Found while reading Java Puzzler book

Today, while solving puzzles from Java Puzzler book I myself created a new Java Puzzle. So, in this blog I am writing about that puzzle.

Puzzle

Will the code given below results in an infinite loop.


public class MyJavaPuzzle {

 public static void main(String[] args) {
 Double i = Double.NaN;
 while(i != i){
 System.out.println("Infinite Loop");
 }
 }
}

Solve this puzzle and have fun. Happy Puzzling!!!

Post your answer and explanation in comments.

Maven classpath ordering lesson learnt

Today, I was working on a user story which spans across two modules(A and B) of our project (C).  As we follow test driven development, so I first wrote a test for the functionality that I need to add in module A and then wrote the piece of code(TDD is not the topic of this blog so please don’t go in detail).  The test passed with the green bar and i moved to the B module. I wrote a test and then  wrote a piece of code but this time test failed with error NoClassDefFoundError: org/objectweb/asm/CodeVisitor . I was a bit surprised why in one module A test is passing and in module B test is failing because both the projects had similar dependencies.

After googling, i found out that this error comes because hibernate has cglib-2.1_3.jar as the dependency which uses older version of asm jar which was having CodeVisitor class. CodeVisitor class has retired and does not exists in newer version of asm jars.  But now the issue was why junit testcase was passing in A module. To find why test case in A module pass I did the maven dependency check on both module using


mvn dependency:tree

In module A, I found out out that it loaded cglib-nodep-2.1_3.jar not cglib-2.1_3.jar . cglib-nodep-2.1_3.jar was loaded because easymockclassextension has dependency on cglib-nodep jar.

In module B, I found out that it loaded cglib-nodep-2.1_3.jar not cglib-nodep-2.1_3.jar. This jar was loaded because hibernate has dependency on cglib jar.

Now the problem was why in A module cglib-nodep jar is loaded but in B module cglib jar is loaded. I looked at the pom.xml and found out that in A module easymockclassextension dependency was declared before the hibernate dependency

<dependencies>
 <dependency>
 <groupId>org.easymock</groupId>
 <artifactId>easymock</artifactId>
 <version>2.5.2</version>
 <scope>test</scope>
 </dependency>
 <dependency>
 <groupId>org.easymock</groupId>
 <artifactId>easymockclassextension</artifactId>
 <version>2.5.2</version>
 <scope>test</scope>
 </dependency>

 <dependency>
 <groupId>log4j</groupId>
 <artifactId>log4j</artifactId>
 <version>1.2.15</version>
 </dependency>
 <dependency>
 <groupId>org.hibernate</groupId>
 <artifactId>hibernate-core</artifactId>
 <version>3.3.2.GA</version>
 </dependency>
 <dependency>
 <groupId>org.hibernate</groupId>
 <artifactId>hibernate-annotations</artifactId>
 <version>3.4.0.GA</version>
 </dependency>
 <dependency>
 <groupId>org.hibernate</groupId>
 <artifactId>hibernate-commons-annotations</artifactId>
 <version>3.3.0.ga</version>
 </dependency>
 <dependency>
 <groupId>org.hibernate</groupId>
 <artifactId>hibernate-entitymanager</artifactId>
 <version>3.4.0.GA</version>
 </dependency>
 <dependency>
 <groupId>junit</groupId>
 <artifactId>junit</artifactId>
 <version>3.8.1</version>
 <scope>test</scope>
 </dependency>
 </dependencies>

In module B pom.xml easymockclassextension dependency was declared after the hibernate dependency.

<dependencies>
 <dependency>
 <groupId>log4j</groupId>
 <artifactId>log4j</artifactId>
 <version>1.2.15</version>
 </dependency>
 <dependency>
 <groupId>org.hibernate</groupId>
 <artifactId>hibernate-core</artifactId>
 <version>3.3.2.GA</version>
 </dependency>
 <dependency>
 <groupId>org.hibernate</groupId>
 <artifactId>hibernate-annotations</artifactId>
 <version>3.4.0.GA</version>
 </dependency>
 <dependency>
 <groupId>org.hibernate</groupId>
 <artifactId>hibernate-commons-annotations</artifactId>
 <version>3.3.0.ga</version>
 </dependency>
 <dependency>
 <groupId>org.hibernate</groupId>
 <artifactId>hibernate-entitymanager</artifactId>
 <version>3.4.0.GA</version>
 </dependency>
 <dependency>
 <groupId>junit</groupId>
 <artifactId>junit</artifactId>
 <version>3.8.1</version>
 <scope>test</scope>
 </dependency>
 <dependency>
 <groupId>org.easymock</groupId>
 <artifactId>easymock</artifactId>
 <version>2.5.2</version>
 <scope>test</scope>
 </dependency>
 <dependency>
 <groupId>org.easymock</groupId>
 <artifactId>easymockclassextension</artifactId>
 <version>2.5.2</version>
 <scope>test</scope>
 </dependency>
 </dependencies>

Because easyclassextension was declared before the hibernate dependency, cglib-nodep was getting loaded hence test was passing.

In this way, I learn that in maven dependencies are loaded in the order they are mentioned in pom.xml. As of version 2.0.9 maven introduced deterministic ordering of dependencies on the classpath.The ordering is now preserved from your pom, with dependencies added by inheritence added last.

Finding all the indexes of a whole word in a given string using java

Intent

To find all the indexes of a whole word in a given searchable string.

Motivation

Today, I had to write a piece of code in which I had to find all the indexes of a particular keyword in a searchable string. Most of the times, when we have to find index of a keyword in a searchable string we use indexOf method of String class.

For example,


String searchableString = “Don’t be evil. Being evil is bad”;

String keyword = “be”;

So, we can find the index of keyword as


int index = searchableString.indexOf(keyword);

This will give us the index of first occurrence of keyword (“be”). Now suppose, we have to find all the indexes of keyword (“be”), we will have to loop over searchableString and find all the indexes of keyword “be”.

This can be done as follows

	public static void findIndexes(){
		String searchableString = "don’t be evil.being evil is bad";
		String keyword = "be";

		int index = searchableString.indexOf(keyword);
		while (index >=0){
			System.out.println("Index : "+index);
			index = searchableString.indexOf(keyword, index+keyword.length())	;
		}

	}

	public static void main(String[] args) {
		findIndexes();
	}

This program will print :

Index :  6

Index : 14

There is a problem in this code as we should not get “Index : 14” because we are looking for a keyword “be” and the index it has found is from word “being” . This just looks for any occurrence of keyword in the string it does not have to be a whole word. To solve this problem, we will be writing a solution using Regular expressions.

Solution

We have to find out the indexes which correspond to the whole word. For example, we should only get “Index : 6” as that corresponds to the keyword “be” not “Index : 14” as it corresponds to the word “being” .

This can be done as follows :-

WholeWordIndexFinder.java

package org.dailywtf.string;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class WholeWordIndexFinder {

	private String searchString;

	public WholeWordIndexFinder(String searchString) {
		this.searchString = searchString;
	}

	public List<IndexWrapper> findIndexesForKeyword(String keyword) {
		String regex = "\\b"+keyword+"\\b";
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(searchString);

		List<IndexWrapper> wrappers = new ArrayList<IndexWrapper>();

		while(matcher.find() == true){
			int end = matcher.end();
			int start = matcher.start();
			IndexWrapper wrapper = new IndexWrapper(start, end);
			wrappers.add(wrapper);
		}
		return wrappers;
	}

	public static void main(String[] args) {
		WholeWordIndexFinder finder = new WholeWordIndexFinder("don’t be evil.being evil is bad");
		List<IndexWrapper> indexes = finder.findIndexesForKeyword("be");
		System.out.println("Indexes found "+indexes.size() +" keyword found at index : "+indexes.get(0).getStart());
	}

}

IndexWrapper.java

package org.dailywtf.string;

public class IndexWrapper {

	private int start;
	private int end;

	public IndexWrapper(int start, int end) {
		this.start = start;
		this.end = end;
	}

	public int getEnd() {
		return end;
	}

	public int getStart() {
		return start;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + end;
		result = prime * result + start;
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		IndexWrapper other = (IndexWrapper) obj;
		if (end != other.end)
			return false;
		if (start != other.start)
			return false;
		return true;
	}

}

Explanation
First of all a regular expression is built using the keyword. Regex \b defines a word boundary. \b allows you to perform a “whole words only” search using a regular expression in the form of \bword\b.
More information on regex could be found at this link.  Next, we just iterate over the matcher till matcher can find any match. Whenever a match is found an wrapper object is created which contains the start and end position of the keyword.

Using the above code, we can find all the indexes of a keyword in a searchable string.

Java Puzzlers on local variable initialization

Intent of my blog

Some time back, i posted a blog on common interview questions on overriding.The blog was very popular on dzone so i decided to write some of the java puzzlers on local variable initialization.One thing which should be kept in mind is that Local variables should be initalized before they are used.Knowing this fact try to answer these questions.

Local Variable Initialization Puzzlers

Question1


public class Question1{
 public static void main(String[] args) {
 int x;
 int y = 10;
 if (y == 10) {
 x = y;
 }
 System.out.println("x is " + x);
 }
}

Question 2


class Question2{
 public static void main(String[] args) {
 int x;
 if(true){
 x = 10;
 }
 System.out.println("x is " + x);
 }
}

Question 3


class Question3{
 public static void main(String[] args) {
 int x;
 final int y = 10;
 if(y == 10){
 x = 10;
 }
 System.out.println("x is " + x);

 }
}

Question 4


class Question4{
 static int y = 10;

 public static void main(String[] args) {
 int x ;
 if(y == 10){
 x = 10;
 }
 System.out.println("x is " + x);
 }
}

Question 5


class Question5{
 static final int y = 10;

 public static void main(String[] args) {
 int x ;
 if(y == 10){
 x = 10;
 }
 System.out.println("x is " + x);
 }
}

Again, like the previous post, i am not posting the solutions because i dont want to take away the fun. So, play with these and have fun.

Overriding Question asked in interviews

Intent of my Blog

Overriding is the concept which is very much asked in the interview.In almost every interview i have given or taken overriding questions were present.So, i decided to document all the possible overriding questions.Try out these questions and have fun.

What is Overriding?

According to wikipedia

“Method overriding, in object oriented programming, is a language feature that allows a subclass to provide a specific implementation of a method that is already provided by one of its superclasses. The implementation in the subclass overrides (replaces) the implementation in the superclass.”

Overriding Questions

Question 1

public class OverridingQuestion1 {

 public static void main(String[] args) {
 A a = new A();
 a.execute();
 B b = new B();
 b.execute();
 a = new B();
 a.execute();
 b = (B) new A();
 b.execute();
 }

}

class A {
 public void execute() {
 System.out.println("A");
 }
}

class B extends A {
 @Override
 public void execute() {
 System.out.println("B");
 }
}

Question 2


class A1 {

 private void prepare(){
 System.out.println("Preparing A");
 }
}

class B1 extends A1 {

 public void prepare(){
 System.out.println("Preparing B");
 }
 public static void main(String[] args) {
 A1 a1 = new B1();
 a1.prepare();
 }
}

Question 3

public class OverridingQuestion3 {

 public static void main(String[] args) {
 A2 a2 = new A2();
 System.out.println(a2.i);
 B2 b2 = new B2();
 System.out.println(b2.i);
 a2 = new B2();
 System.out.println(a2.i);
 }

}
class A2{
 int i = 10;

}
class B2 extends A2{
 int i = 20;

}

Question 4


public class OverridingQuestion4 {

 public static void main(String[] args) {
 A3 a3 = new A3();
 a3.execute();
 B3 b3 = new B3();
 b3.execute();
 a3 = new B3();
 a3.execute();
 b3 = (B3)new A3();
 b3.execute();
 }

}

class A3{
 public static void execute(){
 System.out.println("A3");
 }

}
class B3 extends A3{
 public static void execute(){
 System.out.println("B3");
 }
}

Question 5


public class OverridingQuestion5 {

 public static void main(String[] args) {
 A4 a4 = new B4();
 a4.execute();
 }

}

class A4{
 public void execute() throws Exception{
 System.out.println("A");
 }
}
class B4 extends A4{
 @Override
 public void execute(){
 System.out.println("B");
 }
}

As if now i can think of the above 5 questions. If you have any other overriding question, please put that in comment.
I am not posting solution to these questions. So, try these, and post the solution in comments.