Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How this happens

 
sujith delpachithra
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1638
IntelliJ IDE Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
     
    Ananth Chellathurai
    Ranch Hand
    Posts: 349
    Eclipse IDE Hibernate Spring
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    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
     
    sujith delpachithra
    Greenhorn
    Posts: 12
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    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
    Posts: 15
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    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)
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic