Inheritance question


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 2 of 2

Thread: Inheritance question

  1. #1
    Join Date
    Jan 2005
    Posts
    45

    Inheritance question

    Does anyone know why this code prints out 0 4 3?

    class A {
    public void m() { }
    public A() {
    m();
    }
    }
    class B extends A {
    private int f = 4;
    public void m() {
    System.out.println(f);
    }
    public B() {
    m();
    f = 3;
    m();
    }
    }
    public class Init {
    public static void main(String[] args) {
    B b = new B();
    }
    }

  2. #2
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560
    Its the super class' default constructor that is being
    invoked prior to the value declaration of f in the subclass. The superclass' m() method is overridden
    by the subclass, so the superclass constructor calls
    the subclass' m() method that in turn uses B's class global
    variable f in its print statement. This value is
    already allocated by the compiler but it has not yet
    been assigned the initial value 4, as this assignment procedurally comes after the superclass constructor's invokation
    .
    eschew obfuscation

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center