Topics Index

Class Inheritance Program Output266

If you need explanation Read this topic

If you need Answer Take test on this topic

Class Inheritance Program Output266
What will be the output of the following program?
class ClassInheritance
    public static void main(String s[])
        A a = new A();
        a.i = 4;
        B b = new B();
        b.i = 10;
        b.j = 20;
        a = b; // LINE X

        System.out.println("j = " + a.j); // LINE Y

class A
    int i;

class B extends A
    int j;

A. j = 4
B. j = 20
C. Compilation Error at LINE Y - since the member variable j is not accessible using the reference a
D. Compilation Error at LINE X - since we can not copy a sub-class into a super-class
Topic: Assigning Sub Class Object To Super Class Reference In Java

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 we have the concept of the inheritance where child class inherits the properties of the Parent class except Private we have the class A as the Parent and class B as the class B inherits the Properties of the class A(i will come into class B)..
Execution:in the main() we are creating the instance for the class A than the memory is allocated for the variable i with 4 next we are creating the instance for the class B..than memory is allocated for the i and j than assigned with the 10, we are assigning the child class object to the parent class JAVA PARENT CLASS REFERENCE CAN REFER CHILD CLASS OBJECT
next we are trying to access the variable j which is there in the class we can not access anything from the child class through the Parent so here error will occur

Posted by Uday Kumar    2015-02-23 08:59:59


--Here Concept of Inheritance is used.

--Class A(parent class) contains i varaible
Class B (Child class) contains j variable.

--i is sassigned 4 of object A.i and j are assigned 10 and 20 of class B respectively.

--After that object b is assigned to a.
Here,we are assigning the object of the child class to object of parent class.

--we are printing variable j using object of parent class A,as j is in class B which is child class which is invalid.

--Error at line Y comes since the member variable j is not accessible using the reference a.

Posted by Mânïshå Mùlchåndânï    2015-02-23 17:34:00

This dose is now closed and the winners are Uday Kumar,  for 'First Correct Comment', Mânïshå Mùlchåndânï,  for 'Best Comment' and Uday Kumar for the 'Popular Comment'. The 'lucky liker' is Sai Ram. Please login into Merit Campus using facebook, to claim your recharge. Go to to raise the recharge.

Posted by Merit Campus    2015-02-24 04:10:59

© meritcampus 2019

All Rights Reserved.

Open In App