Menu
Topics Index
...
`

Sub And Super Classes


If you need explanation Read this topic

If you need Answer Take test on this topic

Sub And Super Classes
What will be the output of the following program?
class Super
{
    public int i = 0;

    public Super(String text)
    {
        i = 1;
    }
}

public class Sub extends Super
{
    public Sub(String text)
    {
        i = 2;
    }

    public static void main(String args[])
    {
        Sub sub = new Sub("Hello");
        System.out.println("i = " + sub.i);
    }
}

A. i = 0
B. i = 1
C. i = 2
D. Compilation Error
E. Runtime Error
Topic: Inheritance And Constructors 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 D..here we have the Inheritance concept where sub class inherits the properties of the Super class except private variables and methods..when we create the instance for the Sub class than the memory is allocated for the super class variables also and before executing the sub class constructor system will execute the default constructors in the Super class..if we want call other than default constructors than we need to specify using the super keyword
Execution:
here we have the Super class with the variables i and assigned with the 0 and has 1-arg Constructor which takes arg as String..sub class has the Constructor same as super class...in the main() we create the instance for the Sub class by passing the String than the control goes to the Constructor in the sub class before executing the sub class Constructor than system will try to execute the default constructor in super class but in the Super class we did not have default constructor so compiler will raise an error..

Note: if write one constructor than system wont create the default constrctor

Posted by Uday Kumar    2015-02-12 13:16:33


d

Posted by Shubham Bansal    2015-02-13 03:15:06


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 Maheshwari Natarajan. 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    2015-02-13 03:29:20


© meritcampus 2019

All Rights Reserved.

Open In App