Results 1 to 2 of 2
  1. #1
    himanshu19's Avatar
    himanshu19 is offline Member
    Join Date
    Feb 2010
    Location
    Delhi
    Posts
    6
    Rep Power
    0

    Default constructor calling sequence.

    Hi.
    I have a doubt in following code.
    class Super
    {
    Super(int x)
    {
    System.out.println(x);
    }
    }
    class Sub extends Super
    {
    Sub(int k)
    {
    super(k);
    System.out.println("Inside sub class");
    }
    }
    class Main
    {
    public static void main(String []args)
    {
    Sub obj = new Sub(5);
    }
    }

    We have been told that before sub class constructor super class constructor runs.And if that does happen how come sub class constructor is supplying parameter to super class constructor.Also if we skip the whole constructor of sub class then compiler flashes error.

    Please help.

    THanks.

  2. #2
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,842
    Rep Power
    19

    Default

    The super class constructor is called on the line super(k). If you don't have this line then it will call the default (no parameters) constructor of the parent. If the parent does not have a no parameters constructor then you'll get a compiler error.

    So, the constructor for Sub is called, which then calls the constructor for its parent (Super), before returning to the Sub constructor.

    There are some more steps to this, but that should do you for now.

Similar Threads

  1. Calling a constructor from another one.
    By Somelauw in forum New To Java
    Replies: 1
    Last Post: 11-28-2009, 03:42 PM
  2. calling sequence
    By rocky in forum Web Frameworks
    Replies: 0
    Last Post: 04-27-2009, 08:35 PM
  3. Constructor calling
    By ravian in forum New To Java
    Replies: 2
    Last Post: 12-22-2007, 06:53 PM
  4. Replies: 0
    Last Post: 12-19-2007, 09:10 AM
  5. Replies: 0
    Last Post: 12-19-2007, 09:01 AM

Posting Permissions

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