Wednesday, March 13, 2013

Abstract Class in java

There are situations in which you will want to define a superclass that declares the structure of a given abstraction without providing a complete implementation of every method. That is, sometimes you will want to create a superclass that only defines a generalized form that will be shared by all of its subclasses, leaving it to each subclass to fill in the details. Such a class determines the nature of the methods that the sub c lasses must implement.
 One way this situation can occur is when a super class is unable to create a meaningful implementation for a method. This is the case with the class Figure used in the preceding example. The definition of area( ) is simply a placeholder. It will not compute and display the area of any type of object.
As you will see as you create your own class libraries, it is not uncommon for a method to have no meaningful definition in the context of its superclass. You can handle this situation two ways. One way, as shown in the previous example, is to simply have it report a warning message. While this approach can be useful in certain situations—such as debugging—it is not usually appropriate. You may have methods which must be overridden by the subclass in order for the subclass to have any meaning. Consider the class Triangle. It has no meaning if area( ) is not defined. In this case, you want some way to ensure that a subclass does, indeed, override all necessary methods. Java's
solution to this problem is the abstract method.
You can require that certain methods be overridden by subclasses by specifying the abstract type modifier. These methods are sometimes referred to as subclasser responsibility because they have no implementation specified in the superclass. Thus, a subclass must override them—it cannot simply use the version defined in the superclass. To declare an abstract method, use this general form:
abstract type name(parameter-list);
As you can see, no method body is present. Any class that contains one or more abstract methods must also be declared abstract. To declare a class abstract, you simply use the abstract keyword in front of the class keyword at the beginning of the class declaration. There can be no objects of an abstract class. That is, an abstract class cannot be directly instantiated with the new operator. Such objects would be useless, because an abstract class is not fully defined. Also, you cannot declare abstract constructors, or abstract static methods. Any subclass of an abstract class must either implement all of the abstract methods in the superclass, or be itself declared abstract.
Here is a simple example of a class with an abstract method, followed by a class which implements that method:
// A Simple demonstration of abstract.
abstract class A {
abstract void callme();
// concrete methods are still allowed in abstract classes
void callmetoo() {
System.out.println("This is a concrete method.");
}
}
class B extends A {
void callme() {
System.out.println("B's implementation of callme.");
}
}
class AbstractDemo {
public static void main(String args[]) {
B b = new B();
b.callme();
b.callmetoo();
}
}
Notice that no objects of class A are declared in the program. As mentioned, it is not possible to instantiate an abstract class. One other point: class A implements a concrete method called callmetoo( ). This is perfectly acceptable. Abstract classes can include as much implementation as they see fit.
Although abstract classes cannot be used to instantiate objects, they can be used to create object references, because Java's approach to run-time polymorphism is implemented through the use of superclass references. Thus, it must be possible to create a reference to an abstract class so that it can be used to point to a subclass object. You will see this feature put to use in the next example. Using an abstract class, you can improve the Figure class shown earlier. Since there is no meaningful concept of area for an undefined two-dimensional figure, the following version of the program declares area( ) as abstract inside Figure. This, of course, means that all classes derived from Figure must override area( ).
// Using abstract methods and classes.
abstract class Figure {
double dim1;
double dim2;
Figure(double a, double b) {
dim1 = a;
dim2 = b;
}
// area is now an abstract method
abstract double area();
}
class Rectangle extends Figure {
Rectangle(double a, double b) {
super(a, b);
}
// override area for rectangle
double area() {
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}
}
class Triangle extends Figure {
Triangle(double a, double b) {
super(a, b);
}
// override area for right triangle
double area() {
System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2;
}
}
class AbstractAreas {
public static void main(String args[]) {
// Figure f = new Figure(10, 10); // illegal now
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure figref; // this is OK, no object is created
figref = r;
System.out.println("Area is " + figref.area());
figref = t;
System.out.println("Area is " + figref.area());
}
}
As the comment inside main( ) indicates, it is no longer possible to declare objects of type Figure, since it is now abstract. And, all subclasses of Figure must override area( ). To prove this to yourself, try creating a subclass that does not override area( ). You will receive a compile-time error.
Although it is not possible to create an object of type Figure, you can create a reference variable of type Figure. The variable figref is declared as a reference to Figure, which means that it can be used to refer to an object of any class derived from Figure. As explained, it is through superclass reference variables that overridden methods are resolved at run time.

Super Keyword

The super is a keyword defined in the java programming language. Keywords are basically reserved words which have specific meaning relevant to a compiler in java programming language likewise the super keyword indicates the following :

-- The super keyword in java programming language refers to the superclass of the class where the super keyword is currently being used.
--  The super keyword as a standalone statement is used to call the constructor of the superclass in the base class.
Example to use the super keyword to call the constructor of the superclass in the base class:
public class Class1{
public Class1(String arg){
super(arg);
}


--  The syntax super.<method_Name>() is used to give a call to a method of the superclass in the base class.
--  This kind of use of the super keyword is only necessary when we need to call a method that is overridden in this base class in order to specify that the method should be called on the superclass.
Example to use the super keyword with a method:
public class Class1{
public String String_Method(){
return super.overriden_String_Method();
}


Use of Super:
super is used to reference the parent class when a class extends another

for example, say we have the following 2 classes:
public class animal
{
public void printname()
{
system.out.println("I am an animal");
}
}


public class dog extends animal
{
public void printname()
{
system.out.println("I am a dog");
super.printname();
}
}


We see that dog is a class that extends animal.
if we write something the following

public static void main()
{
Dog d = new Dog()
d.printname()
}



then we will see the Dog class print the following:
I am a dog
I am an animal

The super keyword lets you access the parent class' member functions and variables. The dog class overrides the printname method but you can still call the animal's printname method by using super.printname()

Polymorphism/Method Overloading/Method Overiding

Polymorphism
Polymorphism is the ability of an object to take on many forms. In programming languages polymorphism is the capability of an action or method to do different things based on the object that it is acting upon.

Polymorphism is the capability of an action or method to do different things based on the object that it is acting upon. In other words, polymorphism allows you define one interface and have multiple implementation. This is one of the basic principles of object oriented programming.

Method Overloading

In java method overloading means creating more than one method with same name but with different signature.
 i.e., If name of the method remains common but the number and type of parameters are different, then it is called method overloading in Java.

 Overloaded methods may have different return types. Overloaded Methods: Here, these methods have same return type and name, but the signature(i.e., the parameter it takes are different).

When java encounters a call to an overloaded method, it simply executes the version of the method whose parameters match the arguments used in the call.
Example
public class MethodOver
{
int n1;
int n2;
MethodOver()
{
n1 = 10;
n2 = 20;
}
void square()
{
System.out.println("The Square is " + n1 * n2);
}
void square(int p1)
{
n1 = p1;
System.out.println("The Square is " + n1 * n2);
}
void square(int p1, int p2)
{
n1 = p1;
n2 = p2;
System.out.println("The Square is " + n1 * n2);
}
public static void main(String args[])
{
MethodOver obj1 = new MethodOver();
obj1.square(); //call non parameterise method
obj1.square(4); //call method which has 1 argument
obj1.square(7,8); //call method which has 2 argument
}
}
Output
The Square is 200 The Square is 80 The Square is 56 You can see that here we have 3 square methods with different argument. Its called method overloading.

Method Overiding

Method overriding in Java is a concept based on polymorphism OOPS concept which allows programmer to create two methods with same name and method signature on interface and its various implementation and actual method is called at runtime depending upon type of object at runtime.

 Method overriding allows you to write flexible and extensible code in Java because you can introduce new functionality with minimal code change.

 Method overriding is different than method overloading in Java which we have discussed above. In method overloading, Only name of two overloaded methods are same but method signature must be different while in method overriding, method signature must be same. method overriding represent true polymorphic behaviour, where only name needs to be same underlying method logic can be different.

 Here we will see

-          What is method overriding in Java?
-           Rules to override method in Java?
-          Example of How to override method in Java.

Some Key Points

1) First and most important rule regarding method overriding in Java is that you can only override method in sub class. You can not override method in same class.

2) Second important rule of method overriding in Java that name and signature of method must be same in Super class and Sub class or in interface and its implementation.

3) Third rule to override method in Java is that overriding method can not reduce accessibility of overridden method in Java. For example if overridden method is public than overriding method can not be protected, private or package-private; But opposite is true overriding method can increase accessibility of method in Java, i.e. if overridden method is protected than overriding method can be protected or public.

4) Another worth noting rule of method overriding in Java is that overriding method can not throw checked Exception which is higher in hierarchy than overridden method. Which means if overridden method throws IOException than overriding method can not throw java.lang.Exception in its throws clause because java.lang.Exception comes higher than IOException in Exception hierarchy. This rule doesn't apply to RuntimeException in Java, which is not even need to be declared in throws clause in Java.

5) You can not override private, static and final method in Java. private and static method are bonded during compile time using static binding in Java and doesn't resolve during runtime. overriding final method in Java is compile time error. Though private and static method can be hidden if you declare another method with same and signature in sub class.

6) Overridden method is called using dynamic binding in Java at runtime based upon type of Object. As shown in following example of method overloading.

7) If you are extending abstract class or implementing interface than you need to override all abstract method unless your class is not abstract. abstract method can only be used by using method overriding.

8) Always use @Override annotation while overriding method in Java. Though this is not rule but its one of the best Java coding practice to follow. From Java 6 you can use @Override annotation on method inherited from interface as well.

Method Overriding Example in Java

Now we know what is method overriding in Java and rules of method overriding, It's time to see an example of how to override method in Java. In this example we have used Runnable interface which has an abstract run() method.

 We have two class Task and Periodic Task which implements Runnable interface and override run method. For the purpose of demonstrating how method overriding works in Java we are calling run() method in same thread, which you should not, see difference between run and start method to know why. Because run() is overridden in two separate class, call to run() method will be resolved during runtime depending upon type of Object.




Example
/**
*
* Java program to demonstrate how to override method in Java.
* Overridden method are resolved during runtime based upon type of object
*
*/
public class CollectionTest {

public static void main(String args[]) {

Runnable task = new Task();
task.run(); //call overridden method in Task

task = new PeriodicTask();
task.run(); //calls overridden method in PeriodicTas

}


}

class Task implements Runnable{

@Override
public void run() {
System.out.println("Run method overridden in Task class");
}

}
class PeriodicTask extends Task{

@Override
public void run() {
System.err.println("overridden method run() in PeriodicTask class");
}
}

Output:
Run method overridden in Task class
overridden method run() in PeriodicTask class

That's all on What is method overriding in Java, Rules of method overriding in Java and an example of How to override method in Java. In summary remember to override all abstract method while extending form abstract class or implementing interface. Overridden method are also slower as compared to static and final methods because of dynamic binding but it provides you flexibility, many popular Object oriented design principles are based upon method overriding in Java.