Menu
Topics Index
...
`

Baby Boy Baby Girl


If you need explanation Read this topic

If you need Answer Take test on this topic

Baby Boy Baby Girl
Why does the following program fail to compile?
public class BabyBoyBabyGirl {
    public static void main(String[] args) {
        BabyBoy bb = new BabyBoy();
        bb.print();
        AbstractBaby ab = bb;
        ((BabyBoy) ab).print();
        ab = new BabyGirl();
        ab.print();
        ((BabyGirl) ab).print();
    }
}
interface Baby {
    String getName();
    int getAge();
    void print();
}
abstract class AbstractBaby {
    String name;
    int age;
    public String getName() { return name; }
    public int getAge() { return age; }
}
class BabyBoy extends AbstractBaby implements Baby {
    public void print() {
        System.out.println("Boy " + getName() + "(" + getAge() + ")");
    }
}
class BabyGirl extends AbstractBaby implements Baby {
    public void print() {
        System.out.println("Girl " + getName() + "(" + getAge() + ")");
    }
}

A. Compilation Error because the abstract class does not have abstract methods
B. Compilation Error because we can not call print on bb
C. Compilation Error for some other reason
D. The program compiles with out any errors
Topic: Unknown

If you need explanation Read this topic

If you need Answer Take test on this topic

User comments below. All of them might not be correct.

C. Compilation error occurs because we are calling print method in AbstractBaby object which is not defined.

Posted by Nikhil Sulibhavi    2014-04-14 13:38:31


answer is 'C' because a class that implements a interface should implement all of its methods but in the above code the classes BabyBoy and BabyGirl not implementing all the methods of Baby interface.....

Posted by Sai Teja    2014-04-14 13:39:07


Compilation Error because we cannot call print() using ab..so i think i will go with C

Posted by Deepak Kumar Yadav    2014-04-14 13:42:31


Ans is C..Becz..we calling ab.print();...here ab is na reference of an AbstractBaby class n object is type of BabyGirl..so 1st compiler wil check in Parent class (AbstractBaby becz refeence is type AbstractBaby class) whether print() is there, so here print() is nt there in AbstractBaby class so Compiler wl give error...in the case of BabyBoy we are type casing it into an (BabyBoy) so compilr wl check in BabyBoy class so No error in dat line..

Posted by Uday Kumar    2014-04-14 14:05:43


Congratulations Nikhil Sulibhavi. You are this dose winner. We will send you the link using which you can claim your recharge.

Posted by Merit Campus    2014-04-15 03:55:40


© meritcampus 2019

All Rights Reserved.

Open In App