Menu
Topics Index
...
`

Class Inheritance Program Output268


If you need explanation Read this topic If you need explanation Read this topic

If you need Answer Take test on this topic

Class Inheritance Program Output268
What will be the output of the following program?
class ClassInheritance
{
    public static void main(String s[])
    {
        A a = new A();
        a.i = 21;
        B b = new B();
        b.j = 25;
        printI(a);
        printI(b);  // LINE X
        printJ(b);
    }

    public static void printI(A a1)
    {
        System.out.println(a1.i);
    }

    public static void printJ(B b1)
    {
        System.out.println(b1.j);
    }
}

class A
{
    int i;
}

class B extends A
{
    int j;
}

A. 21
0
25
B. 21
21
25
C. Compilation Error at LINE X - since printI can be only called for objects of type A.
D. ClassCastException will be thrown at runtime
Topic: Passing Sub Class Object As Super Class Reference Is-A Relationship In Java

If you need explanation Read this topic 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.

Ans is A..here we have the Concept of the Inheritance..where Child class Inherit the properties of the parant class..here we have the class A nd class B...

here class b extending the classA..so all properties in the classA get inherited into the classB..in class A we have I and printI() both will inherited into the classB...execution of these properties will depend on the calling object..

Coming to the main class here we create the Instance for the class A so here memory is allocated for the variable i...than we are initializing the a.i=21..next we are creating the instance for the class B than memroy will allocate for the both i n j in in Object b...
we are assigning b.j=25...here we didnt initialize the i in B..means b.i=0 here by default...

next we are calling printI() by passing the instance of class A..here this is call by reference..
in this method we are printing the value of i in the instance a...so it will 21..next twice we are calling printI() by passing the object of the class B..in Java parent class reference can refer child class oBject....in printi() we are printing value of i...already mentioned it is 0..bcz we didnot initialize that value...next we are calling printJ() by passing the object b..there we are printing the value of j in object j..which is 25

Posted by Uday Kumar    2014-12-01 12:47:37


This dose is now closed and the winners are Uday Kumar,  for 'First Correct Comment', Uday Kumar,  for 'Best Comment' and Uday Kumar for the 'Popular Comment'. The 'lucky liker' is Varun Kumar. Please login into Merit Campus using facebook, to claim your recharge. Go to http://java.meritcampus.com/earnings to raise the recharge.

Posted by Merit Campus    2014-12-02 04:01:00


© meritcampus 2019

All Rights Reserved.

Open In App