9.10. A Custom Stack Class

 
[Page 310]

9.5. Overriding vs. Overloading

You have learned about overloading methods in §5.6, "Overloading Methods ." Overloading a method is a way to provide more than one method with the same name but with different signatures to distinguish them. To override a method, the method must be defined in the subclass using the same signature and same return type as in its superclass.

Let us use an example to show the differences between overriding and overloading. In (a), the method p(int i) in class A overrides the same method defined in class B . However, in (b), the method p(double i) in class A and the method p(int i) in class B are two overloaded methods. The method p(int i) in class B is inherited in A .

When you run the Test class in (a), a.p(10) invokes the p(int i) method defined in class A , so the program displays 10. When you run the Test class in (b), a.p(10) invokes the p(int i) method defined in class B , so nothing is printed.

 


Introduction to Java Programming-Comprehensive Version
Introduction to Java Programming-Comprehensive Version (6th Edition)
ISBN: B000ONFLUM
EAN: N/A
Year: 2004
Pages: 503

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net