Java Reference
In-Depth Information
Display 8.4
No Late Binding with Static Methods
1 /**
2 Demonstrates that static methods use static binding.
3 */
4 public class StaticMethodsDemo
5 {
6 public static void main(String[] args)
7 {
8 Sale.announcement();
9 DiscountSale.announcement();
10 System.out.println(
11
Java uses static binding with static
methods so the choice of which
definition of a static method to use is
determined by the type of the variable,
not by the object.
"That showed that you can override a static method " +
"definition.");
12 Sale s = new Sale();
13 DiscountSale discount = new DiscountSale();
14 s.announcement();
15 discount.announcement();
16 System.out.println("No surprises so far, but wait.");
discount and discount2 name the same
object, but one is a variable of type Sale and
one is a variable of type DiscountSale .
17 Sale discount2 = discount;
18 System.out.println(
19 "discount2isaDiscountSaleobject in a Sale variable.");
20 System.out.println("Which definition of announcement() will " +
"it use?");
21 discount2.announcement();
22 System.out.println(
23 "It used the Sale version of announcement()!");
24 }
25 }
Sample Dialogue
This is the Sale class.
This is the DiscountSale class.
That showed that you can override a static method definition.
This is the Sale class.
This is the DiscountSale class.
No surprises so far, but wait.
discount2 is a DiscountSale object in a Sale variable.
Which definition of announcement() will it use?
This is the Sale class.
It used the Sale version of announcement()!
If Java had used
late binding
with static
methods, then
this would have
been the other
announcement.
 
 
Search WWH ::




Custom Search