Total Pageviews

Friday, February 18, 2011

Abstract Class

Abstract Class in java
Abstract classes can be implemented in java. A class is declared abstract using the keyword "abstract" as a prefix. An abstract class may or may not contain any
abstract method. Now lets understand what exactly is an abstract class. Abstract class can be considered as a generic class implemented. Consider the following example :
Their are diffrent classes for various shapes like Rectangle,Square,Circle,Ellipse....
All share some comman properties like color,dimension,fillColor. These comman features/functionality can be kept in a generic class called Shapes. Also each individual class differs in size. Lets say each needs a method changeSize(), The method cannot be kept in superclass Shapes as each class has its own implementation and Shapes being a generic class does not requires this function. If we declare this function as abstract, its signature can be kept in the Shapes class. Each class which extends the Shapes class can write the changeSize method as per its own implementation.

Note that the same can be achieved using interfaces also, but interface cannot have implemenaion of the methods. So the comman methods would be required to be defined in all the classes implementing the interface. Interfaces will be discussed later in the blog,but for the time being just consider it as an implementaion of inheritance in java.

Some key points in abstract classes:
1.A subclass extending an abstract class may or may not define the abstract methods. To do so make the subclass itself as abstract.
2. Abstract class cannot be instantiated.
3. If implementation contains only method signatures and those methods need to be overridden in every sub class then make it as interface rather than abstract class.


An advantage of abstract class over interace is that abstract classes can contain concrete methods also. So in guture if a new method is to be introduced, just add it as a concrete method in abstract class and can be used by the subclass.

Abstract class example:


abstract class Shapes{
private String color; // Should have used Color class instead
public void setColor(String color){
.....
}
public void abstract changeShape(....); //No implementation
}

public class Rectangle extends Shapes{

public void changeShape(...){
//implement the specialises method
}
}


It can also be possible for a class not implementing all the abstract methods. Add another abstract method named "repostion" in Shapes class.
Now do as followed


abstract class Rectangle extends Shapes{
public void changeShape(...){
//implement the specialises method
}
}


class AnotherClass extends Rectangle {

public void reposition(){
//implemet method here
}
}

The above class contaiins all the abstract methods of the Shapes class which were not implemented by Rectangle class.

For more details on abstract class click here .
For comparison between abstract class and interface click here

Thursday, February 17, 2011

Inheritance Continued....

Lets look deeply into inheritance.
Consider the following example :
public class SuperClass{
public String name = "SuperClass Name";
public static String staticName = " SuperClass Static Name";
public static String staticString = "SuperClass Staic String";

public static void printVal(){
.............
}
public void checkVal(){
........
}
}

public class SubClass extends SuperClass{
public String name = "SubClass name";
public static String staticName = "SubClass static name";
protected int staticString = 1;


public static void printVal(){
.............
}
public void checkVal(){
........
}
}

public static void main(....){
SuperClass superWithSuperCon = new SuperClass();
SuperClass superWithSubCon= new SubClass();
SubClass subWithSubCon = new SubClass();

sout(superWithSuperCon.name);
sout(superWithSuperCon.staticName); /*Though being static should have been accessed by using Class name,but java converts the same automatically at compile time(Not recommended)*/
sout(superWithSuperCon..staticString);

sout(superWithSubCon.name);
sout(superWithSubCon.staticName);
sout(superWithSubCon.staticString);

sout(subWithSubCon.name);
sout(subWithSubCon.staticName);
sout(subWithSubCon.staticString);

superWithSuperCon.printVal(); /*SuperClass methods called - Compile time binding*/
superWithSuperCon.checkVal(); /*SuperClass methods called - Run time binding*/

superWithSubCon.printVal(); /*SuperClass methods called - Compile time binding*/
superWithSubCon.checkVal(); /*SubClass methods called - Run time binding*/

subWithSubCon.printVal(); /*SubClass methods called - Run time binding*/
subWithSubCon.checkVal(); /*SubClass methods called - Run time binding*/
}
The output obtained is :
SuperClass Name
SuperClass Static Name
SuperClass Staic String
SuperClass Name
SuperClass Static Name
SuperClass Staic String
SubClass name
SubClass static name
1
The strange behaviour of variable in case 4 is because java does not supports instance variable overriding.Since static variables are class variables they are resolved during compile time only.
Note : Methods of type private/final/static or constructors are resolved at compile time only ie static binding.

Thursday, February 3, 2011

Files with no public classes can have a name that does not match any of the classes in the file.


if you declare a class A in a file called X.java as follows ::

class A{

------

}


the class will compile correctly.

But if you declare the class A as ::

public class A{

}

this will result in an error as --- ( class A is public, must be declared in a file A.java )



This comes under Source File Declaration Rules as defined by java Developers.






Sunday, January 30, 2011

Static Method are always resolved during Compile Time


Consider the following snippet of code :


class SuperClass{

public static void staticMethod(){

System.out.println("SuperClass: inside staticMethod");

}

}


public class SubClass extends SuperClass{

public static void staticMethod(){

System.out.println("SubClass: inside staticMethod");

}


public static void main(String []args){

SuperClass superClassWithSuperCons = new SuperClass();

SuperClass superClassWithSubCons = new SubClass();

SubClass subClassWithSubCons = new SubClass();


superClassWithSuperCons.staticMethod();

superClassWithSubCons.staticMethod();

subClassWithSubCons.staticMethod();

}


}






It will be interesting to note that the output will be


SuperClass: inside staticMethod

SuperClass: inside staticMethod

SubClass: inside staticMethod



Overriding in Java simply means that the particular method would be called based on the run time type of the object and not on the compile time type of it (which is the case with overriden static methods). Okay... Because they are class methods and hence access to them is always resolved during compile time only using the compile time type information.


we're invoking the staticMethod() on an object of Runtime Type as SubClass and not as SuperClass. This confirms that the static methods are always resolved using their compile time type information only Since at compile time first two of the objects contains references to the SuperClass only.





Friday, January 28, 2011

Call by Value vs Call by Reference

We all are familier with two methods of paramter passing - call by value and call by refenence. Now the question arises java supports call by value or call by reference. Lets just for the time being consider few examples and then decide what java follows.

int n = 10;
doubleNumber(n);

Declaration of doubleNumber(...)
public void doubleNumber(int num){ //line 1
num = num * 2; //line 2
}

In the above example when line 1 is encountered,JVM makes a copy of the variable "n". When the control is returend from the function the variable num is no longer in the memory, so originally declared variable "n" remains unchanged in state. Hence by the above example we conclude that java supports call by value.

Now lets try our hands on some objects( Remember int was a primitive type not an object)
Employee emp = new Employee();
raiseSalary(emp);

public void raiseSalary(Employee e){//Line 1
e.setSalary(e.getSalary()*2);
}

Now when the call returns to the caller method surprisingly the value of the salary referred by original object "emp" changes. This happens because at line 1 variable e contains the copy of value at emp ie object refernce. Now both e and emp point to same memory location. So after return object e is collected by the garbage collector but the changes are reflected back . But does that means that java follows pass by reference. Well the answer is NO. Lets understand it with the same Employee class. Take a deep look at the emample below:

Employee emp1 = new Employee();
Employee emp2 = new Employee();

swapEmpObjects(emp1,emp2);

public void swapEmpObjects(Employee obj1,Employee obj2){
Employee temp;
temp = obj1;
obj1 = obj2;
obj2 = temp;
}

Now what happens is obj1 and obj2 contains object reference to emp1 and emp2. After the control returns from the function obj1 and obj2 gets interchanged that is their object reference changes. Since copy of object reference is contained in obj1 and obj2, the objects emp1 and emp2 remains unaltered. In nutshell object referene are passed by value in java. Hence java supports call by value.

Sunday, January 23, 2011

Inheritance and Accessibility


determine which of the print statement has an error if the code is executed
as new B( ).printInfo from main method ---->


class A
{
int x;
private boolean y;
protected String z;
private static int m;
A( )
{
x = 10;
y = true;
z = "mohit";
m++;
}
public int getX( ){return x};
private void getY( ){return y};
public static void incr( )
{
sop( m );
}
}


class B extends A
{
public void printInfo() {
sop( x ); // 1
sop( y); // 2
sop(getX( )); // 3
sop(getY()); // 4
sop(m); // 5
incr();
}

}

Overriding v/s Hiding


Consider the code snippet::


class Foo {
public static void classMethod() {
System.out.println(“classMethod() in Foo”);
}

public void instanceMethod() {
System.out.println(“instanceMethod() in Foo”);
}
}

class Bar extends Foo {
public static void classMethod() {
System.out.println(“classMethod() in Bar”);
}

public void instanceMethod() {
System.out.println(“instanceMethod() in Bar”);
}
}


Let's Consider the following main method to test above code


class Test {
public static void main(String[] args) {
Foo f = new Bar();
f.instanceMethod();
f.classMethod();
}
}



If you run this, the output is

instanceMethod() in Bar
classMethod() in Foo


Although f was declared as a Foo, the actual instance we created was a new Bar(). So at runtime, the JVM finds that f is a Bar instance, and so it calls instanceMethod() in Bar rather than the one in Foo. That’s how Java normally works for instance methods.


It would be better coding style to write either:

Foo.classMethod();

or

Bar.classMethod();

That way, it is crystal clear which class method you would like to call.