Sunday, December 20, 2015

Why we called Java as Platform Independent?

Because of it's JVM implementation. Actually, to be specific Java has a two-step process Compile then Run Compiler makes the byte code and JVM inter-prate this to machine specific language Here is the trick ...Might you have seen when you download JDK there is OS specific version  one is for Unix one is for windows version why so ,because  JVM implementation JVM takes byte code as input and provide m/c language as output so Linux specific JVM makes Linux specific machine code ,windows do the same but as both take byte code as input you can easily export windows compile class  Linux m/c That's why they called Java as a platform independent .

Saturday, November 28, 2015

Overriding in Java in context of design.


Overriding in Java in context of design.

In java Overriding ia a technique by which parent class delegates responsibility to Child. 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 needed ,without these we can't achieve overriding unlike overloading.

As I said child specific behavior executed at run time means Jvm will decide actual Subclass/Object and call it's method so we call it late binding or Dynamic method dispatch.
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 programing is it supports Polymorphic assignment where a parent class reference can point a Subclass object . It will be heavily use in Design pattern or I can say the Whole Design pattern is based on this small concept.

So if Foo is Partn class and Bar is child class we can do that,

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

How can we use this power

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 print() method which is overriden in Bar and Zoo

in Bar
print()
{
Sysout(“Bar”);

in Zoo
print()
{
sysout(“Zoo”);
}
where Foo have Bar and Zoo as child classes

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

So I can easily change the behaviour of the Power class on the fly based on strategy.


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

The method which will be overriden must have sama data signature also retutn type will be same
but onwards java 1.5 return type can be subclasses of parent type we say it Co-varient return.


Please follow the following contracts and burn it in to the head as in Interview or in Exam you can found various types of combination and you have to find the perfect overriden 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 this article, we are going to discuss Overloading and it's complexity.

By definition, if two or more methods in a class or in parent class and child class have 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


Now we are talking about some puzzle over overloading

a. do(int i,long j)
   do(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. do(int i)
do(Integer i) and we call by do(2);

can you guess which method will be called?

Think......

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

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

 can you tell which version will be called?

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

d. do(Integer i) and do(long i) calling with do(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)  aversion
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.





Sunday, November 8, 2015

Understanding Casting in Java

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

a. can I cast any type to another 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 between siblings. So you are able to cast child to parent or parent to child not even siblings !!!!

so if I have a class hierarchy like

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

Then B can allow casting  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 Upcast. 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.

Subcalass = parent properties  + it's own property

so ,

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


DownCasting

When a parent cast to it 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 knows 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 trickiness

What will happen


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

Here when you accessing B's own property it will throw run time exception.
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 runtime exception. So be careful about Downcasting.
















Saturday, November 7, 2015

Understand protected modifier in java

Understanding most critical access modifier  protected in java?

protected is the most critical modifier to understand  .

According to the book, it 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 subclasses 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, you can access properties of other classes by two ways

a. Association (HAS A) 2. inheritance (IS-A)

Scenario a.
packge com.foo;
public class Foo extends Bar
{
Bar bar = new Bar(); // BAR HAS A relationship with FOO(Association)

bar.greet; //not compile no visibility through association

}

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


Scenario b

package com.foo
Class Foo extends Bar
{


System.out.println(greet); //Inherited so it print Hello

}

package com.bar
Class Bar
{
 protected String greet = "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.

For protected the tricky situation arises when  two classes are in the different packages ,as you see Foo is in com.foo and Bar is  in com.bar now the question is, can Foo access Bar's greet variable?

The Answer is simply no as by rule protected is visible only through inheritance so although class Foo extends Bar but we are trying to access greet by association which is not acceptable in java


On other hand in Scenario 2 will be compile fine and show Hello message as Foo inherited Bar's greet property.


Now add another criticality

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.