Tuesday, 30 August 2011

How can a derived class invoke private method of base class?

My question seems little weird but it made be think for a while when i went through a post on Java World. The author of the post Inheritence problem(a demo form Thing in java) asked a similar question what I mentioned in my title.

So here is the exact code.
public class PrivateOverride {
private void f() {
System.out.println("private f()");
}

public static void main(String[] args) {
PrivateOverride po = new Derived();
po.f();
}
}
class Derived extends PrivateOverride {
public void f() {
System.out.println("public f()");
}
}

So the output of this code as mentioned by the author of the code is "private f()". Now the very obvious question arises that how can po which is an object of Derived Class call a private method of PrivateOverride which is its base class.

So I just went through the byte code of the compiled version of the above class and got the invokespecial Opcode. This Opcode was enough to tell the reason why the actual output is obvious. So I will try to explain why it is so?

First we should know
What is invokespecial?

Instance methods normally are invoked with invokestatic, invokevirtual, invokespecial and invokeinterface.
After the release of Java 7, invokedynamic is too added to the above mentioned list.

Invokespecial is used in three situations in which an instance method must be invoked based on the type of the reference, not on the class of the object. The three situations are:

  1. invocation of instance initialization () methods
  2. invocation of private methods
  3. invocation of methods using the super keyword
Our current example lies within the second scenario where we have invocation of private methods. So the method got invoked based on the the type of reference i.e PrivateOverride rather than type of class i.e Derived

So now the question arises why invokespecial? We have other Opcode like invokevirtual which gets invoked for method on the basis of classtype rather than reference type. So lets discuss why invokespecial Opcode is used for private methods.
But we should know the difference between invokevirtual and invokespecial.
Invokespecial differs from invokevirtual primarily in that invokespecial selects a method based on the type of the reference rather than the class of the object. In other words, it does static binding instead of dynamic binding. In each of the three situations where invokespecial is used, dynamic binding wouldn't yield the desired result.

Here is an example that explains the reason more clearly


class BaseClass {

private void demoMethod() {
System.out.println("Demo method from Base class.");
}

void exampleMethod() {
interestingMethod();
}
}

class DerivedClass extends Baseclass {

void demoMethod() {
System.out.println("Demo method from Derived class");
}

public static void main(String args[]) {
DerivedClass derived = new Subclass();
derived.exampleMethod();
}
}


So now when you invoke main method in DerivedClass, it must print "Demo method from Base Class." But if invokevirtual would have been used, it would print "Demo method from Derived Class." Why? Because the virtual machine would choose the demoMethod() to call based on the actual class of the object, which is DerivedClass. So it will use DerivedClass's demoMethod(). On the other hand, with invokespecial the virtual machine will select the method based on the type of the reference, so BaseClass's version of demoMethod() will be invoked.

Feel free to share your thoughts on the post through comments.

References
http://www.javaworld.com/community/node/8089
http://www.artima.com/underthehood/invocationP.html

Submit this post on reddit

Monday, 29 August 2011

How to use Type safe dependency injection in Spring 3?

Before jumping to Type Safe Dependency Injection from Spring, I would like to to discuss the way we have been doing it earlier. We have been using dependency injection by type with the help of Autowired annotation from Spring.
Something like this  would inject the spring bean.
@Autowired
private  StudentDao studentDao;  // Autowires by type. Injects the instance whose type is StudentDao
But if we have more than one spring bean of one type then we use Qualifier Annotation along with Autowired which in facts injects the spring bean by name.

An application context with :
<bean id="studentDao1" class="StudentDao" />
<bean id="studentDao2" class="StudentDao" />


So now if we have two instances of StudentDao (studentDao1 and studentDao2), we can inject spring bean by name.
@Autowired
@Qualifier("studentDao1")
private StudentDao studentDao1;

@Autowired
@Qualifier("studentDao2")
private StudentDao studentDao2;
Same thing can be achieved with Resource annotaion specified by JSR-250. So we can inject a bean into a field or single parameter method with this annotation. Autowired is little more flexible than Resource since it can be used with multi parameter method as well as constructors.
We can inject bean by name with Resource annotation in the following manner.

@Resource
private StudentDao studentDao1;
Type safe dependency injection in Spring 3

Define a custom annotation using @Qualifier

To identify the injected bean without specifying the name, we need to create a custom annotation. This is an equivalent procedure to the use of JSR 330 annotations(Inject) in CDI.
@Target({ElementType.Field, ElementType.Parameter})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @Interface Student  {
}
Now assign this custom annotation to implementation of EntityDao Interface
@Component
@Student
public class StudentDao implements EntityDao   {
}
@Component tells Spring that this a bean definition. @Student annotation is used by Spring IoC to identify StudentDao as EntityDao's implementation whenever reference of EntityDao is used.
Inject the bean using @Autowired and custom qualifier
Something like this.
@Autowired
@Student
private EntityDao studentDao; // So the spring injects the instance of StudentDao here.
This makes less use of String-names, which can be misspelled and are harder to maintain.

Feel free to express your doubts, suggestions and corrections (if any) on the post .

Submit this post on reddit

Friday, 19 August 2011

Why do we need Type Inference from Java 7?


Every good programmer likes to write a concise but effective and optimized code. Type Inference is a way introduced in JDK 7 which will surely give you benefits of less typing. Its been a long time that you have using the java code in following manner.
List<string> names = new ArrayList<string>();
Map<string, Object> objectMap = new HashMap<string, Object>();

But have you ever thought of code duplication while initializing the specific implementation of Collections? Why there is a need to write the parameters two times during an intialization?
Now most of you would be thinking of initializing as a raw types as you had been doing in previous JDK version.
Something like this.
List<string> names = new ArrayList();
Map<string, object=""> objectMap = new HashMap();

So whats new in JDK 7? What benefits you will have from the new feature?
So first we need to understand the difference between raw type and generic type intialization.

A statements like this ensures that the implementation will contain the same parameter as specified during initialization.
List<string> names = new ArrayList<string>();
In the following example, the compiler generates an unchecked conversion warning because the HashMap() constructor refers to the HashMap raw type, not the Map<String, List<String>> type:
Map<String, List<String>> myMap = new HashMap(); // unchecked conversion warning

Diamond Operator
Okay Now I will introduce the new feature of JDK 7.
So we have something called Diamond operator in JDK 7 which reduces your extra typing while initialization.
Syntax:
List<string> names = new ArrayList<>();

So it not only reduces your code but also ensures the type checking.
Here is a more clear example explaining the benefits of type inference.

Advanced Example:


class Demo {
void printStudentNames(List<string> names)	{
for(String name:names)	{
System.out.println("String name:"+name);
}
}

public static void main(String[] args)	{
Demo demo = new Demo();
demo.printStudentNames(new ArrayList<>());	  // It saved typing here in a method call too.
List<string> names = new ArrayList<>();
printStudentNames(names);
List<string> copyOfNames = new ArrayList<>(names);  // It saved typing here in a copy contructor invocation too.
}
}

Now what are its limitations?
It won't work in the case you use wildcards.
Something like this
Class Tree<t>	{

public void demoFunction(List<t> objList)	{
List<t> copyOfNames = new ArrayList<t>(objList);   //This is not gonna work.
}
}

In the above case the arguments passed in the copy constructor should be Collection<? extends T>
So it wont accept the above inference type.

Feel free to write your reviews about the post in comments. And I will love to reply of doubts on the same.


Submit this post on reddit

Sunday, 14 August 2011

A better approach to handle Java NullPointerException



The most common exception that you meet coding in java whether you are a junior or an Intermediate level programmer. Before coming to the solution proposed and added in the new Java update, I would like to discuss the strategies that most of us should follow while handling this common but peculiar exception. There are two approaches that people generally follow.

1.) Treat Null as a valid response
2.) Treat Null as an invalid response

Life is very easy for the people who go with the second approach. Taking null as an invalid response you won't be getting a null reference calling any of your methods or API. So where there is a situation where null is to be handled, throw InvalidArgumentException or try assert. Assert throws an exception whenever the condition given to it is false. And in case you are using collections always return an empty collection instead of null reference

But most of you will disagree going with the second approach since most of us have been using the first approach from the very start. You have been using APIs where you don't have the control over the code. Now with the first case you never know where you are going to meet with null reference. So you have nothing left except a valid check for the null reference.

Java is up with a solution to your valid null checks.

Null Safe Operators from Java
Use Elvis or other null safe operators to get every NPE handled.

i) Elvis Operator
It results to the value on the left hand side if not null else right hand side is evaluted.
Example:
Integer a = getInteger();  // may be null
int i = a ?: -1;  // no NPE from unboxing  
So here the value of a will be assigned to i only if a is not equal to null.

ii) Null Safe operator
It is similar to member selection dot operator(.). Just a valid null check is added to its definition.
Example:
class Student {    private Parent parent; // may be null
public Parent getParent()	{
return this.parent;    }
} class Parent {     String name; // may be null
private Address address; // may be null
public Address getAddress ()	{
return this.address;    }
}
class Address {
private String locaton;
private private String street;
String houseNumber;
public String getLocation ()	{
return this.location;    }
}

So without this Java feature you would have written something like this
String location= null;
if (student != null && student.getParent() != null && student.getParent().getLocation != null) {
location= student.getParent().getLocation();
} else {
location= "unknown";
}

But now with Java's Null safe operator you code can be eased down to something like this.
String location = student?.getParent()?.getLocation() ?: "unknown";

So what are the major benefits and disadvantages using this features.

Advantages
  • Since the null checks get automatically handled with the use of these operators so now you can focus more on the business logic.
  • Code size and complexity gets reduced
Disadvantages
  • It encourages rather than discouraging the use of null reference in the APIs.
Other Solutions to Valid Null Checks
  1. Depending upon what kind of objects you are checking you may be able to use some of the classes in the apache commons such as: apache commons lang and apache commons collections

    Example:

    String name;
    ...
    if( StringUtils.isBlank( name) ) {
    ///do something
    }

    or (depending on what you need to check):

    String name;
    ...
    if( StringUtils.isEmpty( name) ) {
    ///do something
    }

    The StringUtils class is only one of many; there are quite a few good classes in the commons that do null safe manipulation.
  2. If you switch to JetBrains Idea, a Java ide, you can use some annotations developed by them.
    Basically, you've got:
    @Nullable
    and
    @NotNull
    You can use these annotations in method and parameters, like this:
    @NotNull public String getName() {
    return "Saurab Parakh";
    }
    
    
    When you use the first getName() function in this way:
    public static void main(String[] args)
    {
    if(getName() != null) {
    System.out.println(getName());
    }
    }
    Now the JetBrains idea compiler will tell you that the null check is useless, since the getName() will never return null. Using parameter
    void someMethod(@NotNull someParameter) { }
    if you write something like:
    someMethod(null);
    This won't compile.


    So how did you find the post? Please share your reviews about the post.
Submit this post on reddit

Tuesday, 9 August 2011

Improved and Better Exception Handling from Java 7

So as a continuation of my previous post Features from Java-7 that you will love being a developer, today I am going to introduce the very new Improved Exception Handling in Java SE 7.

I)Mutiple Exceptions handling
Before the launch of Java SE 7 we were habitual of writing code with multiple catch statements associated with a try block.
A very basic Example:
try {
// some instructions
}
catch(ATypeException e) {
}
catch(BTypeException e) {
}
catch(CTypeException e) {
}

But now with the latest update on Java, instead of writing multiple catch statements we can handle multiple exceptions within a single catch clause. Here is an example showing how this feature can be achieved.

try {
// some instructions
}
catch(ATypeException|BTypeException|CTypeException ex) {
throw e;
}

So multiple Exceptions in a single catch clause not only simplifies the code but also reduce the redundancy of code.

Essential Points to be noted:
  • In the case of multiple Exception parameters within a single catch clause, the parameter is implicitly final means the exception ex cannot be assigned a new value.
II)Intelligence of Throws clause

Method declaration includes the exceptions which the method is going to throw in its throws clause. And these exceptions in the throws clause are nothing but the exceptions thrown within the catch clause

So till now the approach we follow is

/* Let us assume that Exception is the base class and all other exceptions extend this class*/
public void demoMethod() throws Exception {
try {
// some instructions
throw new ATypeException();
}
catch(Exception e) {
throw e;
}
}


So in the above example the exception thrown is of Exception type. But now with Java 7 you can be more specific throwing an exception. Instead of Exception(Super class or base class) type, we can directly use ATypeException in the throws clause. In previous version of java it would have thrown a compile time error("unreported exception Exception ") for the above code.

Case which to not follow the above mentioned feature
If we assign a new value to the exception e within the catch clause then we need to throw the exception of type Exception instead of being specific.

Behind the Scenes
So what were the changes that were required to implement this feature?
First of all the grammar of the language was changed and multiple exceptions were allowed as parameters within the catch clause with the 'OR' operator as a separator.

Wasn't there any case where this implementation contradict the previous version of Java code?
Yes there is a case which should have been handled in the earlier version and which can break your previous code if we compile it again with the latest java updates.
If we have nested try catch and the inner catch clause throws an exception that is not exactly the type which is thrown to the outer catch then in such scenario you will be getting a compile time exception with Java 7 but it works well with previous version of java.

Example:
/* Let us assume that Exception is the base class and all other exceptions extend this class*/

try {
throw new A();
}
catch(Exception e) {
try{
throw e;
}
catch(B b) { // The code will never reach here.
}
}

In the above example Exception e can be of A type but can never be of B type. So the inner catch with B parameter is never reached.

Next Feature: Why do we need Type Inference from Java 7?

10 Reasons not to buy Windows Phone 7


No USB drive mode
Windows Phone 7 OS doesn't have have USB drive mode by default. However, the same can be enabled using some user created hacks.

No peer to peer gaming
Windows Phone 7 OS doesn't support peer to peer gaming. This is where you miss all the fun related to the games.

No file system – apps can only access their own directory
Windows Phone 7 OS doesn't have a file system. The applications installed can only access their own directory.

No Flash
This one's a stunner, but Ballmer has reportedly been talking with Adobe so WP7's lack of Flash may only be temporary.

No multitasking
Another stunner. Once Android showed how multitasking could be done on a mobile phone, even Apple was forced to play catch-up. For Microsoft to unveil a new, "modern" OS and not include multitasking is puzzling to say the least.

No Unified Email
The whole idea behind Microsoft's hub-based gestalt is to focus on activities rather than sterile apps. But "email" isn't included under "messaging," and there are separate apps for Outlook, Hotmail, Gmail and every other email source. This does't meet Microsoft's "fewer clicks" design goals and could prove to be frustrating to users.
 
No Cut-And-Paste
We know this is only temporary — the last item mentioned at the Windows Phone announcement was that cut-and-paste would be part of a software upgrade early next year. But like all of Windows Phone 7's other missing tidbits, not including this basic capability, which caused iPhone users to loudly howl, makes it seem Windows Phone 7 was rushed to market before it was ready.

Where Are the Apps?
Several high-profile apps such as eBay, IMDb, and Sims 5 were showcased at the Windows Phone 7 unveiling, but the only other mention of apps was vague generalities — hundreds of thousands of developers downloading the SDK and thousands of apps expected. When and how many? Excellent question.

No Desktop Client
I've said it before and I'll say it again: without a desktop client, the mainstream phone-using consumers Microsoft hopes to convert will become frustrated if they don't have an easy of way of loading music, videos, photos, etc., onto their handsets.

It's Three Years Too Late
Windows Phone 7 is in about the same shape Apple's iPhone OS was in 2007. Individually, no single one of these missing capabilities is a problem. But reviewers are likely to take Microsoft to task for missing so many of them, leading to negative comparisons with iPhone and Android Microsoft can barely afford.





VirtualBox OSE conflict with KVM

When starting virtual machine, VirtualBox will give error status:
"Failed to start the virtual machine XYZ
VirtualBox can't operate in VMX root mode. Please disable the KVM kernel extension, recompile your kernel and reboot.
(VERR_VMX_IN_VMX_ROOT_MODE).


 There are different ways to solve this;
  1. In terminal type : modprobe -r kvm_intel   
  2. Remove kvm and Qemu kvm through terminal
    $ sudo apt-get purge kvm 
    $ sudo apt-get purge qemu-kvm    

    The two mentioned above will either unload the kvm modules or   remove them totally from your system.In case you don't want to remove kvm from your system and still use Virtualbox (though this would be hardly the case in my opinion)

    modify /etc/init/qemu-kvm.conf :
     $ vi /etc/init/qemu-kvm.conf  (This step needs to be performed by the “Root” user to be successful)
     
    Change ,
    start on runlevel [2345]
    to
    #start on runlevel [2345]
     
    effectively disabling this line.


    Run;
    $ sudo initctl reload (This too requires sudo privileges) afterwards to reload the settings.
    This should make the kvm module loading manual, with modprobe or with
    sudo stop qemu-kvm
    and
    sudo start qemu-kvm

    Related Posts