• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

plz explain and tell out put

 
Akhilesh Yadav
Ranch Hand
Posts: 46
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class A {
public A(){
super();
System.out.println("instantiate a parent");
}
}

public class B extends A{
public void child (){
System.out.println("instantiate a child");
}
}
public class C {
public static void main(String [] args){
A a = new B();
}
}

wht would be the output :-
a) intantiate a parent
b)intantiate a child
c) both a and b
 
Roy Simon
Ranch Hand
Posts: 62
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
the output would be option a followed by option b
the reason is that before a subclass object is created its super class instance is initiated first (its like every sublass object has a super class object inside it)

Regards
Simon
 
Chandrasekhar Mangipudi
Ranch Hand
Posts: 118
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Instantiate a parent is the right answer.Here we are creating object for B class and before the execution of the B class Constructor it calls super class constructor of A class and executes it without complation error.
 
Asha Pathik
Ranch Hand
Posts: 143
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

public class A
{
public A() // Class A's constructor
{
super();
System.out.println("instantiate a parent");
}
}

public class B extends A // Class B with no constructor
{
public B()
{
super();
}

public void child () // Not a constructor
{
System.out.println("instantiate a child");
}
}

public class C
{
public static void main(String [] args)
{
A a = new B();
}
}

1)In Java whenever you do not provide a constructor for a class compiler inserts the default contructor with a call to super class constructor in your class.

2)Now, due to inheritance whenever you create a subclass's object it first invoke its super class's contructor and after the superclass object creation completes then subclass constructor is executed.

In your program 1) & 2) both are valid as you don't have a constructor for a subclass B which is extending from class A. So when you write

A a= new B();

compiler invokes its default constructor in which there is (no print system)just a call to super, so it will print

instantiate a parent

nothing more.

Since public void child(){System.out.println("instantiate a child");}
never gets executed, you will never see this message printed on the screen.

Hope this helps you.
Asha
 
Sandeep Singh Kunwar
Ranch Hand
Posts: 52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think 'Asha Pathik' has explained everything in this regard.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic