Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Program Output

 
G. Graz
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok, new to Java so please go easy on me ! I can not figure what the output of the follow code is ? Can anyone help me ? Thank you so much in advance !!



Also form that would this be a legal statement ?

B b2 = new A () ;

Thanks again everyone !!
 
Santhi Bharath
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
when you are creating an object of subclass,

there is implicit super() {which calls super class constructor }
statement prior to all the statements of the subclass constructor
so the output should be

B.f()
B.g()
A.h()
B.f()
B.g()

here overridden methods of B will execute i.e f and g and then h of A will execute and then constructor remaining statements i.e call to f and g will execute.

if you specify static qualifier for the methods then

A.f()
A.g()
A.h()
B.f()
B.g()


finally we can assign sub class object to super class object.but, we can't assign super class object to sub class object.


so,

B b=new A();

will go with error

but,

A b=new B();

is equal to

A a =new A();
B b=new B();
a=b;
 
G. Graz
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ok, great !! I am understanding it a bit more ! Thank you again !
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Although you have correctly worked out how your class is running, don't call public methods from a constructor in "real life." Either call private methods or public final methods.
If you did anything peculiar in the overridden methods you could introduce errors into the superclass which can be very difficult to find.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic