CSC/ECE 517 Fall 2007/wiki2 8 c9: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
No edit summary
No edit summary
 
(26 intermediate revisions by the same user not shown)
Line 1: Line 1:
                                                Topic 8 : Overloading Vs Overriding
                                               
<center><b> Topic 8 : Overloading Vs Overriding</b></center>


Overloading vs. overriding. Skrien delineates the difference between overloading and overriding in Section 2.8. He does this in the context of Java. How do other languages make this distinction, especially those like CLOS that define multi-methods?
Overloading vs. overriding. Skrien delineates the difference between overloading and overriding in Section 2.8. He does this in the context of Java. How do other languages make this distinction, especially those like CLOS that define multi-methods?




</b>Polymorphism</b>
<h2><b>Polymorphism</b></h2>
  Polymorphism is usually expressed by the phrase “One interface, multiple methods”. This allows a super class to specify methods that will be common to all of its subclasses, while allowing the subclasses to define their own specific methods.
It means design a generic interface and use it for group of related activities. This helps reduce complexity by allowing the same interface to be used to specify a general class of action. It is the compiler’s job to select the specific action (that is, method ) as it applies to each situation.
<b> Overloading</b>
  In Java it is possible to define 2 or more methods within the same class that share the same name, as long as their parameter declarations are different. The methods are said to be overloaded. This process is referred as method overloading. It is one of the way by which java implements polymorphism.Java uses the type and /or number of arguments to determine which of the overloaded methods to be overloaded. The overloaded methods may differ in return type or the number of parameters in the method call.


Example
Polymorphism is usually expressed by the phrase “One interface, multiple methods”. This allows a super class to specify methods that will be common
to all of its subclasses, while allowing the subclasses to define their own specific methods.It means design a generic interface and use it for group
of related activities. This helps reduce complexity by allowing the same interface to be used to specify a general class of action. It is the
compiler’s job to select the specific action (that is, method ) as it applies to each situation.
 
<h2><center><b> Overloading</b></center></h2>
 
In Java it is possible to define 2 or more methods within the same class that share the same name, as long as their parameter declarations
are different. The methods are said to be overloaded. This process is referred as method overloading. It is one of the way by which java
implements polymorphism.Java uses the type and /or number of arguments to determine which of the overloaded methods to be overloaded.
The overloaded methods may differ in return type or the number of parameters in the method call.
 
<h1>Example</h1>
<pre>
<pre>


class Overload{
class Overload  
void show() {
{
  void show() {
 
  System.out.println(" There are no parameters in this method");
            }


  System.out.println(“ There are no parameters in this method”);
  void show(int a) {
}
  System.out.println("this has one parameter : a" +a);
                  }
 
  void show(int a,int b){
  System.out.println("this has 2 parameters a"+a+ "b:"+b);
                        }


void show(int a) {
  double show(double a){
System.out.println(“this has one parameter : a” +a);
  System.out.println("this has a double parameter a"+a);
  return a*a
                        }
}
}


Void show(int a,int b){
System.out.println(“this has 2 parameters a”+a+ “b:”+b);
}


Double show(double a){
System.out.println(“this has a double parameter  a”+a);
Return a*a
}
}


Class overloadtest {
class overloadtest {
Public static void main(String args[]){
public static void main(String args[]){
 
Overload obj=new Overload();
Overload obj=new Overload();
Double result;
double result;


Obj.show();
obj.show();
Obj.show(10);
obj.show(10);
Obj.show(10,20);
obj.show(10,20);
Result=obj.show(100.5);
result=obj.show(100.5);
System.out.println(“result of obj.show(100.5) is” + result);
System.out.println("result of obj.show(100.5) is" + result);
}
                                    }
}
                    }
</pre>
</pre>




Output
 
<h3><b>Output</b></h3>


   
   
There are no parameters in this method
There are no parameters in this method<br>
this has one parameter : a 10<br>
this has 2 parameters a 10 b 20<br>
this has a double parameter a 100.5<br>
the result of obj.show(100.5) is 10100.25<br>


this has one parameter : a 10
this has 2 parameters a 10 b 20
this has a double parameter a 100.5
the result of obj.show(100.5) is 10100.25


<h1><center><b>Overriding</b></center></h1>


Overriding occurs only with respect to inheritance and occurs when a subclass has a method with the same signature as a parent's method.
The method in the subclass is said to override the method in the superclass. Java always invokes the most derived viewable version of a
method based on the scope of the present reference.  However , if we wish to access superclass version of overridden method, then we
can use the keyword “super” and then access it.


      <b>Overriding</b>


      Overriding occurs only with respect to inheritance and occurs when a subclass has a method with the same signature as a parent's method. The method in the subclass is said to override the method in the superclass. Java always invokes the most derived viewable version of a method based on the scope of the present reference.  However , if we wish to access superclass version of overridden method, then we can use the keyword “super” and then access it.
<h1>Example</h1>


<pre>
class Figure {
double length;
double breadth;


Example
  Figure(double a, double b)
  {
    length =a;
    breadth=b;
  }


<pre>
  double area(){
Class Figure {
  System.out.println(“area for figure is undefined”);
Double length;
  return 0;
Double breadth;
                }
 
  }
Figure(double a, double b)
{
Length =a;
Breadth=b;
}


Double area(){
System.out.println(“area for figure is undefined”);
Return 0;
}
}


Class rectangle extends Figure {
class Rectangle extends Figure {
Rectangle (Double a, double b) {
Super(a,b);
Rectangle (Double a, double b) {
}
super(a,b);
                                }


// override the area for rectangle
  // override the area for rectangle
Double area()   
  double area()   
{
{
System.out.println(“inside area for rectangle”);
  System.out.println(“inside area for rectangle”);
Return length* breadth
  return length* breadth
}
  }
}
                                }




Class triangle extends figure{
class Triangle extends Figure {
Triangle (double a,double b)
Triangle (double a,double b)
{
{
Super(a,b);
  super(a,b);
}
}
// override area for triangle
// override area for triangle
Double area() {
double area() {
System.out.println(“inside area of triangle”);
System.out.println(“inside area of triangle”);
Return length*breadth /2;
return length*breadth /2;
}
                }
}
                                }        




Class areastest{
class areastest {
Public static void main(String args[]){
public static void main(String args[]){
Figure obf=new figure(10,10);
Figure obf=new figure(10,10);
Rectangle obr=new rectangle(25,50);
Rectangle obr=new rectangle(25,50);
Line 118: Line 135:


Figure ref;
Figure ref;
Ref=obr;
ref=obr;
System.out.println(“area is”+ ref.area());
System.out.println(“area is”+ ref.area());


Ref=obt;
ref=obt;
System.out.println(“area is”+ ref.area());
System.out.println(“area is”+ ref.area());


Ref=obf;
ref=obf;
System.out.println(“area is”+ ref.area());
System.out.println(“area is”+ ref.area());
}
}
Line 131: Line 148:
</pre>
</pre>


<b>Output</b>  
<h3><b>Output</b></h3>
Inside area for rectangle
 
Area is 1250
Inside area for rectangle<br>
Inside area of  triangle
Area is 1250<br>
Area is 400
Inside area of  triangle<br>
Area for figure is undefined
Area is 400<br>
Area is 0
Area for figure is undefined<br>
Area is 0<br>
 
 
<b><h1>Differences between Overloading and Overriding </h1></b>
 
 
 
<table border="3">
<tr>
<td><b>Overloaded</b></td>
<td><b>Overridden</b></td>
</tr>
<tr>
<td>supplements each other</td>
<td>replaces the method it overrides</td>
</tr>
<tr>
<td> can exist in any number within same class </td>
<td> Each method in a parent class can be overridden at most once in any one class</td>
</tr>
<tr>
<td>must have different arguments </td>
<td> must have argument list of identical type and order </td>
</tr>
<tr>
<td> return type may be freely chosen </td>
<td> return type must be identical </td>
</tr>
<tr>
<td> determined at compile time </td>
<td> determined at run time </td>
</tr>
</table>
 
 
Note: Overloaded methods should be used sparingly, as they can make code much less readable.
 
 
<h1><center> <b>CLOS (Common Lisp Object System)</b> </center></h1>
 
The Common Lisp Object system comprises a set of tools for developing object-oriented programs in Common Lisp. An object-oriented program is usually designed and constructed in modular fashion. The object oriented style of programming makes it practical to organize large programs; it helps in decomposing large programs into smaller modules.
Some of the benefits of CLOS are
1) CLOS program is conveniently extensible
2) CLOS provides tools that can help you design modular and extensible programs
3) Client programs benefit from a well defined interface
4) The program more closely resembles the world it is modelling.
 
<h2><b>Multi Methods</b></h2>
 
Many object-oriented programs can be written with methods that specialize only one parameter. However, it is sometimes useful to write methods that specialize more than one parameter. These are called multi-methods. For multi-methods, the determination of which method is more specific involves more than one parameter. The parameters are considered lexicographically from left to right. (Hence earlier parameters are more important than later ones.)
 
Example
Consider a scenario where a company sells various software products, each of which can run on a variety of operating systems. The installation procedure depends on type of the software product and on the type of operating system. The company wants to provide a generic installation program to automate the installation process.
We want to provide one top level function for installing any of our supported products on any of the supported operating systems. We do this with a generic function install which expects a software product as its first argument and an operating system as its second argument.
 
<pre>
(defgeneric install (software-product  operating sytem)
  (: documentation "installs software on operating system"))
 
 
;;; Method 1
(defmethod install ((sw basic-product) (os basic-os))
  body)
 
;;; Method 2
(defmethod install ((sw basic-product) (non-os )
  (error "cannot install because ~A is not a recognised operating system." non-os))
 
 
;;; Method 3
(defmethod install ((non-product) (os basic-os )
  (error "cannot install because ~A is not a recognised software product." non-product))
;;; Method 4
(defmethod install ((non-product) (non-os )
  (error "cannot install because ~A is not a recognised software product and ~A is not a recognised operating system" non-product non-os))
 
</pre>
 
CLOS allows methods for the same generic function to specialize any for the required parameters. The methods for install take advantage of that flexibility:
<table border="3">
<tr>
<td><b>Method</b></td>
<td><b>Lambda_list</b></td>
</tr>
<tr>
<td>Method1</td>
<td>((sw basic-product) (os basic-os))</td>
</tr>
<tr>
<td>Method2</td>
<td>((sw basic-product) non-os)</td>
</tr>
<tr>
<td>Method3</td>
<td>(non-product  (os basic-os))</td>
</tr>
<tr>
<td>Method4</td>
<td>(non-product  non-os)</td>
</tr>
</table>
 
When install is called, CLOS looks for the applicable methods. A method is applicable if each specialized parameter is satisfied by the corresponding argument to the generic function.
An unspecialized parameter is equivalent to the class t being the parameter specializer. Since all objects are of type t, an unspecialized parameter is always satisfied by the argument. Thus method 4 is applicable for any two arguments, no matter what their types are.
Suppose install is called with 2 valid arguments. Here  * life* is instance of life, and *genera* is instance of genera.
<pre>
;;; Here install is called with two valid arguments.
(install *life* *genera*)
 
Both methods 1 and 2 are applicable
;;; Method 1 is applicable because these forms are true.
(typep *life* 'basic-product)
(typep *genera* 'basic-os)
 
;;; Method 2 is applicable because these forms are true.
(typep *life* 'basic-product)
(typep *genera* 't)
 
Similarly methods 3 and 4 are also applicable:
;;; Method 3 is applicable because these forms are true.
(typep *life* 't)
(typep *genera* 'basic-os)
 
;;; Method 4 is applicable because these forms are true.
(typep *life* 't)
(typep *genera* 't)
</pre>
 
 
When CLOS finds more than one applicable primary method, only the most specific one is called. Thus CLOS must rank the applicable methods in the order of precedence.
 
Just by looking at the lambda-lists, we can conclude that method 1 is most specific(it specializes both parameters) and method 4 is least specific(because it does not specialize either of the parameter). However it is not intuitive which of methods 2 and 3 is more specific. CLOS ranks 2 as more specific than 3 because of left to right order.
<b>Thus the precedence order is
(method-1 method-2 method-3 method-4)</b>
 
 
<h2><b>Overriding in CLOS</b></h2>
 
CLOS allows multiple inheritance. A class can inherit from all of its superclasses, both direct and indirect. When something is specified by more than one of these superclasses, in Common Lisp, there are rules that can refer to a total ordering of all the superclasses of a class. This ordering is called the class precedence list of the class. Classes earlier in the list are considered more specific than later ones, and they may override information provided by less specific classes.
The following 2 rules are used for finding a unique order in CLOS.<br>
<b> 1)Each class is more specific than its superclasses. </b><br>
CLOS allows a class to have more than one direct superclass. So CLOS provides multiple inheritance., and the rule above is no longer enough.<br>
<b> 2)For a given class, superclasses listed earlier are more specific than those listed later. </b><br>
With multiple inheritance, ordering superclasses becomes harder. Suppose we have
(defclass a (b c) ...)
Class A is more specific than B or C. However if something is specified by both B and C, which overrides the other is given by the rule: Superclasses listed earlier in the class definition are considered more specific (relative to the class being defined) than those listed later.<br>Thus these rules are used in CLOS for deciding the order of preference is.
 
 
 
 
<h1><center><b>Conclusion</b></center></h1>
Java uses the type and /or number of arguments to determine which of the overloaded methods to be overloaded.
On the other hand, languages which use multi-methods like CLOS call the most specific method when they find more than
one applicable primary method. CLOS ranks the applicable methods in the order of precedence.
While overriding, Java always invokes the most derived viewable version of a method based on the scope of the present reference.
On the other hand, CLOS uses a class precedence list using certain rules to decide which method to override.
 
 
 
<h1><b>References</b></h1>
 
1) Complete Reference in Java Text book<br>
2) Object Oriented Programming in Common Lisp Text book<br>
3) A Brief guide to CLOS              http://www.aiai.ed.ac.uk/~jeff/clos-guide.html<br>
4) Overloading and Overriding in Java  http://ww2.cs.fsu.edu/~steele/FALL_03_CIS3931/REFERENCES/OVER/over.html<br>
5) Overloading and overriding in Java  http://smccd.net/accounts/greenm/Overloading.pdf<br>
6) Wiki reference to CLOS              http://en.wikipedia.org/wiki/Common_Lisp_Object_System

Latest revision as of 12:44, 24 October 2007

Topic 8 : Overloading Vs Overriding

Overloading vs. overriding. Skrien delineates the difference between overloading and overriding in Section 2.8. He does this in the context of Java. How do other languages make this distinction, especially those like CLOS that define multi-methods?


Polymorphism

Polymorphism is usually expressed by the phrase “One interface, multiple methods”. This allows a super class to specify methods that will be common to all of its subclasses, while allowing the subclasses to define their own specific methods.It means design a generic interface and use it for group of related activities. This helps reduce complexity by allowing the same interface to be used to specify a general class of action. It is the compiler’s job to select the specific action (that is, method ) as it applies to each situation.

Overloading

In Java it is possible to define 2 or more methods within the same class that share the same name, as long as their parameter declarations are different. The methods are said to be overloaded. This process is referred as method overloading. It is one of the way by which java implements polymorphism.Java uses the type and /or number of arguments to determine which of the overloaded methods to be overloaded. The overloaded methods may differ in return type or the number of parameters in the method call.

Example


class Overload   
{
  void show() {

   System.out.println(" There are no parameters in this method");
             }

  void show(int a) {
  System.out.println("this has one parameter : a" +a);
                   }

  void show(int a,int b){
  System.out.println("this has 2 parameters a"+a+ "b:"+b);
                         }

  double show(double a){
  System.out.println("this has a double parameter  a"+a);
  return a*a
                        }
}



class overloadtest {
public static void main(String args[]){

Overload obj=new Overload();
double result;

obj.show();
obj.show(10);
obj.show(10,20);
result=obj.show(100.5);
System.out.println("result of obj.show(100.5) is" + result);
                                     }
                     }


Output


There are no parameters in this method
this has one parameter : a 10
this has 2 parameters a 10 b 20
this has a double parameter a 100.5
the result of obj.show(100.5) is 10100.25


Overriding

Overriding occurs only with respect to inheritance and occurs when a subclass has a method with the same signature as a parent's method. The method in the subclass is said to override the method in the superclass. Java always invokes the most derived viewable version of a method based on the scope of the present reference. However , if we wish to access superclass version of overridden method, then we can use the keyword “super” and then access it.


Example

class Figure {
double length;
double breadth;

  Figure(double a, double b)
  {
    length =a;
    breadth=b;
  }

   double area(){
   System.out.println(“area for figure is undefined”);
   return 0;
                }
   }


class Rectangle extends Figure {
 
 Rectangle (Double a, double b) {
 super(a,b);
                                }

  // override the area for rectangle
  double area()  
 {
  System.out.println(“inside area for rectangle”);
  return length* breadth
  }
                                }


class Triangle extends Figure {
 Triangle (double a,double b)
 {
  super(a,b);
 }
 // override area for triangle
 double area() {
 System.out.println(“inside area of triangle”);
 return length*breadth /2;
                }
                                }          


class areastest {
public static void main(String args[]){
Figure obf=new figure(10,10);
Rectangle obr=new rectangle(25,50);
Triangle obt=new triangle(20,40);

Figure ref;
ref=obr;
System.out.println(“area is”+ ref.area());

ref=obt;
System.out.println(“area is”+ ref.area());

ref=obf;
System.out.println(“area is”+ ref.area());
}
}

Output

Inside area for rectangle
Area is 1250
Inside area of triangle
Area is 400
Area for figure is undefined
Area is 0


Differences between Overloading and Overriding


Overloaded Overridden
supplements each other replaces the method it overrides
can exist in any number within same class Each method in a parent class can be overridden at most once in any one class
must have different arguments must have argument list of identical type and order
return type may be freely chosen return type must be identical
determined at compile time determined at run time


Note: Overloaded methods should be used sparingly, as they can make code much less readable.


CLOS (Common Lisp Object System)

The Common Lisp Object system comprises a set of tools for developing object-oriented programs in Common Lisp. An object-oriented program is usually designed and constructed in modular fashion. The object oriented style of programming makes it practical to organize large programs; it helps in decomposing large programs into smaller modules. Some of the benefits of CLOS are 1) CLOS program is conveniently extensible 2) CLOS provides tools that can help you design modular and extensible programs 3) Client programs benefit from a well defined interface 4) The program more closely resembles the world it is modelling.

Multi Methods

Many object-oriented programs can be written with methods that specialize only one parameter. However, it is sometimes useful to write methods that specialize more than one parameter. These are called multi-methods. For multi-methods, the determination of which method is more specific involves more than one parameter. The parameters are considered lexicographically from left to right. (Hence earlier parameters are more important than later ones.)

Example Consider a scenario where a company sells various software products, each of which can run on a variety of operating systems. The installation procedure depends on type of the software product and on the type of operating system. The company wants to provide a generic installation program to automate the installation process. We want to provide one top level function for installing any of our supported products on any of the supported operating systems. We do this with a generic function install which expects a software product as its first argument and an operating system as its second argument.

(defgeneric install (software-product   operating sytem)
   (: documentation "installs software on operating system"))


;;; Method 1
(defmethod install ((sw basic-product) (os basic-os))
   body)

;;; Method 2
(defmethod install ((sw basic-product) (non-os )
   (error "cannot install because ~A is not a recognised operating system." non-os))


;;; Method 3
(defmethod install ((non-product) (os basic-os )
   (error "cannot install because ~A is not a recognised software product." non-product))
;;; Method 4
(defmethod install ((non-product) (non-os )
   (error "cannot install because ~A is not a recognised software product and ~A is not a recognised operating system" non-product non-os))

CLOS allows methods for the same generic function to specialize any for the required parameters. The methods for install take advantage of that flexibility:

Method Lambda_list
Method1 ((sw basic-product) (os basic-os))
Method2 ((sw basic-product) non-os)
Method3 (non-product (os basic-os))
Method4 (non-product non-os)

When install is called, CLOS looks for the applicable methods. A method is applicable if each specialized parameter is satisfied by the corresponding argument to the generic function. An unspecialized parameter is equivalent to the class t being the parameter specializer. Since all objects are of type t, an unspecialized parameter is always satisfied by the argument. Thus method 4 is applicable for any two arguments, no matter what their types are. Suppose install is called with 2 valid arguments. Here * life* is instance of life, and *genera* is instance of genera.

;;; Here install is called with two valid arguments.
(install *life* *genera*)

Both methods 1 and 2 are applicable 
;;; Method 1 is applicable because these forms are true.
(typep *life* 'basic-product)
 (typep *genera* 'basic-os)

;;; Method 2 is applicable because these forms are true.
(typep *life* 'basic-product)
(typep *genera* 't)

Similarly methods 3 and 4 are also applicable:
;;; Method 3 is applicable because these forms are true.
(typep *life* 't)
(typep *genera* 'basic-os)

;;; Method 4 is applicable because these forms are true.
(typep *life* 't)
(typep *genera* 't)


When CLOS finds more than one applicable primary method, only the most specific one is called. Thus CLOS must rank the applicable methods in the order of precedence.

Just by looking at the lambda-lists, we can conclude that method 1 is most specific(it specializes both parameters) and method 4 is least specific(because it does not specialize either of the parameter). However it is not intuitive which of methods 2 and 3 is more specific. CLOS ranks 2 as more specific than 3 because of left to right order. Thus the precedence order is (method-1 method-2 method-3 method-4)


Overriding in CLOS

CLOS allows multiple inheritance. A class can inherit from all of its superclasses, both direct and indirect. When something is specified by more than one of these superclasses, in Common Lisp, there are rules that can refer to a total ordering of all the superclasses of a class. This ordering is called the class precedence list of the class. Classes earlier in the list are considered more specific than later ones, and they may override information provided by less specific classes. The following 2 rules are used for finding a unique order in CLOS.
1)Each class is more specific than its superclasses.
CLOS allows a class to have more than one direct superclass. So CLOS provides multiple inheritance., and the rule above is no longer enough.
2)For a given class, superclasses listed earlier are more specific than those listed later.
With multiple inheritance, ordering superclasses becomes harder. Suppose we have (defclass a (b c) ...) Class A is more specific than B or C. However if something is specified by both B and C, which overrides the other is given by the rule: Superclasses listed earlier in the class definition are considered more specific (relative to the class being defined) than those listed later.
Thus these rules are used in CLOS for deciding the order of preference is.



Conclusion

Java uses the type and /or number of arguments to determine which of the overloaded methods to be overloaded. On the other hand, languages which use multi-methods like CLOS call the most specific method when they find more than one applicable primary method. CLOS ranks the applicable methods in the order of precedence. While overriding, Java always invokes the most derived viewable version of a method based on the scope of the present reference. On the other hand, CLOS uses a class precedence list using certain rules to decide which method to override.


References

1) Complete Reference in Java Text book
2) Object Oriented Programming in Common Lisp Text book
3) A Brief guide to CLOS http://www.aiai.ed.ac.uk/~jeff/clos-guide.html
4) Overloading and Overriding in Java http://ww2.cs.fsu.edu/~steele/FALL_03_CIS3931/REFERENCES/OVER/over.html
5) Overloading and overriding in Java http://smccd.net/accounts/greenm/Overloading.pdf
6) Wiki reference to CLOS http://en.wikipedia.org/wiki/Common_Lisp_Object_System