jQuery in Action, 2nd edition*
The moose likes Beginning Java and the fly likes How this happens Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How this happens" Watch "How this happens" New topic
Author

How this happens

sujith delpachithra
Greenhorn

Joined: Oct 14, 2008
Posts: 12
class A{
public A(){
System.out.println("A:A");
this.foo();
}
public void foo(){
System.out.println("A:Fooo");
}
}

class B extends A{
int i =90;
public B(){
i =98;
System.out.println("B:B");

}

public void foo(){
System.out.println("b:Fooo");
System.out.println(i);
}
}

public class NewClass {

public static void main(String[] args) {

A a = new B();
}
}

This prints
A:A
b:Fooo
0
B:B

But, it is not the expected value. Explain this?
Nitesh Kant
Bartender

Joined: Feb 25, 2007
Posts: 1638

Hi Sujith,

Welcome to javaranch.
We are a very friendly community and do not have many rules.
However, there are a few guidelines that helps you get good answers.
It will be nice if you can go through this on how to ask questions in the ranch. Specifically,
  • CarefullyChooseOneForum (This is more of a beginners question)
  • UseCodeTags


  • Coming to your question.

    sujith: But, it is not the expected value.


    So, what is it that you expected?


    apigee, a better way to API!
    Ananth Chellathurai
    Ranch Hand

    Joined: Nov 21, 2007
    Posts: 349

    Hi Sujith,

    I got

    A:A
    b:Fooo
    0
    B:B


    as the answer. Whats your problem with this? More details would get better replies.

    Regards
    Ananth Chellathurai


    Ananth Chellathurai [Walk on software]
    sujith delpachithra
    Greenhorn

    Joined: Oct 14, 2008
    Posts: 12
    Before constructing the B object it calls B's foo(). if it created B object it should call B's constructor first. i am too confused with the result. explain how the results are printed?
    Dmitri Bichko
    Greenhorn

    Joined: Jun 16, 2007
    Posts: 15
    Originally posted by sujith delpachithra:
    Before constructing the B object it calls B's foo(). if it created B object it should call B's constructor first. i am too confused with the result. explain how the results are printed?


    No-argument base-class constructors are implicitly called from the extending class' constructor.

    It should make sense if you think of B's constructor as:



    foo() isn't called before constructing B, but while.

    (I'm not sure this is an advanced question)
     
    I agree. Here's the link: http://aspose.com/file-tools
     
    subject: How this happens
     
    Similar Threads
    How to print java Map name/value pair through JSON object in JS
    Doubts in Mock exam HFSJ
    overriding exception
    GC question
    Coffee Cram - Chapter 5 (Attributes and Listeners)