CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Guest

    Constructor Question

    Suppose I create a constructor for my base class A. Then another class B (sans constructor) inherits from that class. If I say
    B test = new B(12,3); // assuming A had a constructor that takes 2 ints


    Will Java call the constructor from the base class??


  2. #2
    Join Date
    Apr 1999
    Location
    Bangalore,India
    Posts
    43

    Re: Constructor Question

    Normally when u create an object of a class which extends from a Other class, first the consrtructor of the super class is called and then its constructor is called. But which constructor is called depends upon what u have given in the constructor of the sub class. For example,
    public class A{
    public A(){
    }
    public A(int i1,int i2){
    System.out.println("I am in Constructor A");
    }
    }

    public class B extends A{
    public B(int i1,int i2){
    super(i1,i2);
    System.out.println("I am in Constructor B");
    }
    }

    In the above case u have explicity called the super class constructor in the constructor of B. So first the Super class constructor will be get called. If u won't mention super(int,int), then it will call the default constructor of the Super class i.e. the constructor with no arguments. If there is no such constructor in the super class then u will get compilation error saying that "No constructor matching A() found in class A". U have to take care this in the super class. U have to write a default construtor in class A.
    Also if u r making a call to the super class constructor, it has to be the first call in the constructor of sub class.

    I hope this will answer your question.

    regards,
    arun...


Posting Permissions

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





Click Here to Expand Forum to Full Width

Featured