Results 1 to 3 of 3
  1. #1
    pepe34 is offline Member
    Join Date
    Oct 2011
    Posts
    3
    Rep Power
    0

    Default constructor vs overridable method

    Hi,

    I have a question about overridable method call in constructor.

    For example:

    class A {
    public A() {
    fun();
    prv_fun();
    }
    public void fun() {
    System.out.println("A");
    }
    private void prv_fun() {
    System.out.println("PRV A");
    }
    }

    public class B extends A {
    public B() {
    fun();
    }
    public void fun() {
    System.out.println("B");
    }
    public static void main(String[] args) {
    B obj = new B();
    }
    }

    the result is:

    B
    PRV_A
    B

    Why does the constructor of class A invoke class B fun() method and class A prv_fun() private method ?

    Constructor A bytecode:
    public <init>()V
    L0
    LINENUMBER 2 L0
    ALOAD 0
    INVOKESPECIAL java/lang/Object.<init>()V
    L1
    LINENUMBER 3 L1
    ALOAD 0
    INVOKEVIRTUAL A.fun()V
    L2
    LINENUMBER 4 L2
    ALOAD 0
    INVOKESPECIAL A.prv_fun()V
    L3
    LINENUMBER 5 L3
    RETURN
    L4
    LOCALVARIABLE this LA; L0 L4 0
    MAXSTACK = 1
    MAXLOCALS = 1

    and it contains command INVOKEVIRTUAL A.fun()V,
    so why does the constructor of class A invoke B.fun() ?

    Thanks

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: constructor vs overridable method

    Quote Originally Posted by pepe34 View Post
    so why does the constructor of class A invoke B.fun() ?
    It's being called inside of a B object, and the magic of polymorphism allows it to call B's method. This is one reason it is potentially dangerous to call overridable methods inside of a class's constructor.

  3. #3
    pepe34 is offline Member
    Join Date
    Oct 2011
    Posts
    3
    Rep Power
    0

    Default Re: constructor vs overridable method

    Ok, but why the bytecode contains "INVOKEVIRTUAL A.fun()V" ?

    I wonder if dynamic linking works here.

Similar Threads

  1. Final variable-constructor method.
    By D4rkNrG in forum New To Java
    Replies: 9
    Last Post: 10-13-2010, 11:18 AM
  2. Method and Constructor
    By swikar.java in forum New To Java
    Replies: 7
    Last Post: 10-21-2008, 02:41 PM
  3. Method & Constructor
    By swikar.java in forum New To Java
    Replies: 4
    Last Post: 10-21-2008, 01:31 PM
  4. Differences between constructor and method
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 12-19-2007, 08:53 AM
  5. Java constructor method
    By carl in forum New To Java
    Replies: 2
    Last Post: 07-31-2007, 02:15 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •