waltermilner

Untitled

Apr 26th, 2016
233
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.63 KB | None | 0 0
  1. // Problem calling a method in a constructor
  2. // See below
  3. // Constructing Sub invokes the constructor of the base class, and this invokes method
  4. // But Sub has overridden method, and the over-ridden method has been invoked.
  5. // If we've forgotten that method is involved in the object construction, this might be a disaster
  6.  
  7. public class Test {
  8.  
  9.   public static void main(String[] args) {
  10.    Sub sub=new Sub(); // outputs Sub
  11. }
  12. }
  13.  
  14. class Base
  15. {
  16.   Base()
  17.   {
  18.     method();
  19.   }
  20.  
  21.   void method()
  22.   {
  23.     System.out.println("Base");
  24.   }
  25. }
  26.  
  27. class Sub extends Base
  28. {
  29.   void method()
  30.   {
  31.     System.out.println("Sub");
  32.   }
  33. }
Advertisement
Add Comment
Please, Sign In to add comment