Saturday, November 28, 2015

Overriding in Java in context of design.


Overriding in Java in context of design.

 


 While you are going for an Interview for a Lead or Developer role. The interviewer will definitely ask you some questions on Overriding and try to puzzle you.


In this tutorial, I try to cover all topics of Overriding so you feel comfortable and easily answer  whatever questions they ask


Definition of Overriding:
In Java, Overriding is a technique by which parent class delegates responsibility to Child. A child can define child specific behavior which will be executed at run time.

From the above definition, it is clear that to do Overriding Parent class and child class is must need, without Child class, we can't achieve overriding, unlike overloading.

Please remember , The interviewer may ask you-- can it be possible to do overriding without child class?

As I said child specific behavior executed at run-time what I mean by this is the  JVM will decide which  Subclass/Object's method it has to call,  so we call it late binding or Dynamic method dispatch.Because runtime JVM decides what to do not at compile time.

Question: What is late binding/ Dynamic method dispatch in Java

If you don't get my point don't worry follow example will clear the concept.



Before dig down to Overriding details let clear one small thing.


The big power of OOP programming is it supports Polymorphic assignment where a parent class reference can point a Subclass object. It will be heavily used in Design pattern or I can say the Whole Design pattern is based on this small concept.

 

Q: What do you mean by polymorphic assignment and Why it is important?


Let's understand why this is important.


say  Foo is Parent class and Bar is child class so we can do that,


Foo foo = new Bar();//Polymorphic assignment.

By parent reference, we can point child Object. It is logical as child inherited all properties of the parent so whatever in parent must have in the child unless properties are private in a parent.


What is the benefits of polymorphic assignment?
 let see the small code

Class Power
{

private Foo f;

public setFoo(Foo f)
{
this.f = f;

}

public void show()
{
f.print();
}
}

Class Foo has a print() method which is overridden in Bar and Zoo two subclasses of Foo

overridden  in Bar
public void print()
{
Sysout(“Bar”);
}


overridden in Zoo
public void print()
{
sysout(“Zoo”);
}

overriding java


so by the setFoo method in Power class, I can easily set Bar or Zoo instance at run time based on some business logic .so when it calls show method based on the subclass it prints Bar or Z

So I can easily change the behavior of the Power class on the fly based on strategy. It is the crux of Strategy design pattern.

But remember, As SetFoo method takes parent reference what ever method are in parent class  you can call those, all Association condition applied here. So if any new method added in subclass that is not visible by parent reference.

Qustion : expect a coding snippet here where interviewr add a method in child and try to call it by polymorphic refrence.

To make it visible you need to do down-casting.

Tip: Always use @Override annotation if you are using Java 5 or more to make sure if maintains all rules of overriding.


To do a perfect overriding we have to follow some rules.

The method which will be overridden must have same data signature also return type will be same

but onwards java 1.5 return type can be subclasses of parent type we say it Co-variant return.
 Q: What is covarient return?


Please follow the following contracts and burn it into the head as in Interview or in Exam you can found various types of combination and you have to find the perfect overridden method.
1. The argument list must exactly match that of the overridden method. If they
don't match, you can end up with an overloaded method .


2. The return type must be the same as, or a subtype of, the return type declared
in the original overridden method in the superclass. we say it covariant return


3. The access level can't be more restrictive than the overridden methods.
The access level CAN be less restrictive than that of the overridden method.
Instance methods can be overridden only if they are inherited by the subclass.
A subclass within the same package as the instance's superclass can override
any superclass method that is not marked private or final. A subclass in a
different package can override only those non-final methods marked public
or protected (since protected methods are inherited by the subclass).

4. The overriding method CAN throw any unchecked (runtime) exception,
regardless of whether the overridden method declares the exception.

5. The overriding method must NOT throw checked exceptions that are new
or broader than those declared by the overridden method. For example, a
the method that declares a FileNotFoundException cannot be overridden by a
the method that declares an SQLException, Exception, or any other non-runtime
exception unless it's a subclass of FileNotFoundException.

6. The overriding method can throw narrower or fewer exceptions.

Monday, November 9, 2015

Overloading in java

In Interview, you can expect a bunch of questions over overloading and believe me those are very tricky, If you are not understand overloading then it will be very tough to crack interview as this is the fundamentals of Java.

NB: Many people think overloading is very easy but go through the article you will find it is not so easy when overloading comes with boxing,varags, and Widening. 


In this article, we are going to discuss Overloading and it's complexity.

By definition, if two or more methods in a class or in a parent class and child class have the same name but different data signature irrespective of return type called Overloading.


so following example is a  valid overloading is

public class OverLoadtest {


    public void test(int i)
    {
        System.out.println("overloaded 1");
    }

    public void test(long j)
    {
        System.out.println("overloaded 2");
    }

    public static void main(String[] args) {
   
        OverLoadtest test = new OverLoadtest();
   
    }

}

Overloading has some contracts when you are doing a over loading please remember this contracts.

a.  Overloaded methods MUST change the argument list.
b.  Overloaded methods CAN change the return type.
c. Overloaded methods CAN change the access modifier.
d  Overloaded methods CAN declare new or broader checked exceptions.

so

public void do(int i) throws AirithmeticException;
public void do(long j)
public int do(double j)
private int do(String j)
private void do()
throws Exception;

all are valid overloading

overloading in java
Add caption




Now we are talking about some puzzle over overloading

a. doX(int i,long j)
   doX(long j,int i,)
is this  a valid overloading???

The answer is Yes Data signature is different although method meaning is same as only arguments are swap their space.

b. doX(int i)
doX(Integer i) and we call by doX(2);

can you guess which method should be called?

Think......

It will call do(int i)
 as in overloading precedence always over in primitive type;

c. doX(Integer i);
doX(int ... i); now calling doX(2);

 can you tell which version will be called?

It calls do(Integer i); as in overloading, Boxing has precedence over varargs.

d. doX(Integer i) and doX(long i) calling with doX(2)

now here it will call do(long i) as in overloading primitive widening has precedence over boxing .

e. do(Object i)
do(Long i)
 call with do(2) can you tell which version will be called

it calls do(Object i)  version
In Overloading Boxing then widening is permissible, mean here conversion is
int->Integer->Object (boxing then Widening)
 but do(Long i) int->long->Long widening then boxing will not allow.

so remember the following rules to determine which version will be called.

1. Primitive widening uses the "smallest" method argument possible.
2. Used individually, boxing and var-args are compatible with overloading.
3. You can't widen from one wrapper type to another. (IS-A fails.)
4. You can't widen and then box. (An int can't become a Long.)
5. You can box and then widen. (An int can become an Object, via Integer.)
6. You can combine var-args with either widening or boxing.

see Overriding related interview questions also.





Sunday, November 8, 2015

Understanding Casting in Java

Understanding Casting in Java

In Java, Casting means to cast a class to another class. This definition has two catch points.


a. Can I cast any Java /custom type(class) to another Java/custom type: No You can only cast those classes to one another which are in the same inheritance tree. You can go back and forth but you are not allowed to cast one class to another type class. So you are able to cast child to parent or parent to child, but not able to cast between another type of class even siblings !!!!

Example :

Class A : Base class
Class B : subclass of A
Class C : subclass of A
Class D : Subclass of B

Then we can cast B to A and D but not C.

b. How many  types of Casting are there in Java:

There are two types of casting
a. Upcasting
b. DownCasting

Upcasting : When a Subclass is cast to parent that is called Upcasting. In Java, every polymorphic assignment is that type of casting. To do that you do not have to bother about explicit casting. this is logical because inheritance means inheriting   the properties of a parent into the child so you can easily say, property exists in the child also exists in the parent.

Subclass = parent properties  + it's own property

so ,

A a=null;
B b =new B(); //B extends A
a =b;//Up-casted no need to explicit casting.


DownCasting:
When a parent cast to its child it called downcasting and explicitly casting is needed here. It is logical as Parent does not know which child it needs to be cast more over parent does not know about Child's own properties.
so
Parent = subclass - Subclass own property


B b =null;   //B extends A
A a = new B();//polymorphic assignment.
b =(B)a; // need  explicit casting as ref a does not know about Object B.




Now add some complexity

Try to guess What will happen?

B b =null;   //B extends A
A a = new A();
b =(B)a; // need  explicit casting.

as although here, Compiler will not complain, but b reference holds an object of A, so when you called class B's own property through reference b. Actual  A object does not have that property and throws a run-time exception. So be careful about Downcasting.

Diagram


















Saturday, November 7, 2015

Understand protected modifier in java

Understanding most critical access modifier  protected in java?


We all know Java has three access modifiers a, public b. protected c. private and four access levels  a.public b. protected c. private d. default among them protected is the most critical modifier to understand.


Definition of protected
protected is same as default modifier, which can be accessed by other classes in the same package but the only difference is it can also be accessed by sub classes from outside packages through inheritance.

Now there are two catch points

1. What do you mean by accessed?
2. What do you mean by access through inheritance?

1. What do you mean by accessed?


In Java, we can access properties of other classes by two ways

a. Association (HAS A)
b. Inheritance (IS-A)

Scenario a.

package com.bar;
public class Bar
{
 protected String greet = "Hello";
}



package com.foo;
public class Foo extends Bar
{
Bar bar = new Bar(); // Bar HAS A relationship with Foo(Association)

bar.greet; //not compiled as no visibility through association

}



Scenario b

package com.bar
Class Bar
{
 protected String greet = "Hello";
}


package com.foo
Class Foo extends Bar
{


System.out.println(greet); //accessd through Inheritence so it prints Hello

}



Association means a class has a reference to another class  as you see in Scenario a.

Inheritance means  a class inheriting parent class property.
The Answer is  no as by rule protected is visible only through inheritance so although class Foo extends Bar but we are trying to access greet variable through association which is not acceptable in Java



On another hand, in Scenario 2 will compile fine and show Hello as Foo inherited Bar's greet property though Inheritance by definitions which is acceptable.

Now, adding bit complexity in it
suppose,
the class zoo is in the package com.foo now If I write following code snippet in Zoo


Foo foo = new Foo();
foo.greet;

will it be compile?

Think about it.......

The Answer is no as I said earlier by Association (different package ) you can't ever access greet. but in Same package you do.

See the relationship picture to remember the rule.

Protected access modifiers