Menu
Topics Index
...
`

Example2949


If you need explanation Read this topic

If you need Answer Take test on this topic

Example2949
What will be the output of the following program?
public class Example {
    public static void main(String args[]) {
        Rails rails = new Rails();
        rails.i = 10;
        rails.j = 20;
        Ruby ruby = new Ruby();
        ruby.i = 50;
        ruby.j = 100;
        compareHead(ruby, rails);
    }
    public static void compareHead(Ruby ruby, Ruby rails) {
        System.out.println(ruby.getTotal() > rails.getTotal() ? "ruby" : "rails");
    }
}

class Head {
    int i, j;
    int getTotal() {
        return i + j;
    }
}
class Ruby extends Head {
    int k;
}
class Rails extends Ruby {
    int l;
}

A. ruby
B. rails
C. Compilation Error
D. Runtime Error
Topic: Passing Sub Class Object As Super Class Reference

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 3 classes Head,Ruby,Rails..here Head is the Parent class of the Both Rubya dn Rails calsses..here we have the multilevel inheritance..

Inheritance is the process of deriving the properites of the Parent class into the Child class

here class Ruby extending the Head so the properties(i,j,getTotal()) in Head are inherited into the class Ruby..now Ruby will have the i,j,k getTotal()

class Rails extending the Ruby so it will get the Properties(i,j,k,getTotal()) of the class Ruby..
Rails will have i,j,k,k getTotal()

Coming to the Execution of the Code:
starting from the main we create the instance for the class Rails so and initialized the values of i,j to 10,20 and others will remain with default values..

create another Instance for the class Ruby and initialized the variables i,j to 50,100,others will remain with default values..

we have the compareHead() which takes the 2 params (Ruby n Rails)..it is an static method we can invoke it directly Bcz even main() is static..

here we are comparing the sum the i n j values in each objects..here we are calling getTotal() with ruby so it will invoke the getTotal() in Ruby class so it will return the i+j..actually this is an inherited method..it will return 150..ruby--i=100,ruby-->j=50,rails.getTotal() will return the 30 ruby--i=10,ruby-->j=20..so here in condtional operator condtion is true so the it will print ruby as output

Posted by Uday Kumar    2014-12-09 12:46: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 Ankur Verma. 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-10 09:36:03


© meritcampus 2019

All Rights Reserved.

Open In App