logo

CuriousTab

CuriousTab

Discussion


Home Java Programming Declarations and Access Control See What Others Are Saying!
  • Question
  • What will be the output of the program?
    class A 
    {
        final public int GetResult(int a, int b) { return 0; } 
    } 
    class B extends A 
    { 
        public int GetResult(int a, int b) {return 1; } 
    } 
    public class Test 
    {
        public static void main(String args[]) 
        { 
            B b = new B(); 
            System.out.println("x = " + b.GetResult(0, 1));  
        } 
    }
    


  • Options
  • A. x = 0
  • B. x = 1
  • C. Compilation fails.
  • D. An exception is thrown at runtime.

  • Correct Answer
  • Compilation fails. 

    Explanation
    The code doesn't compile because the method GetResult() in class A is final and so cannot be overridden.

    More questions

    • 1. What will be the output of the program?
      class Super
      { 
          public int i = 0; 
      
          public Super(String text) /* Line 4 */
          {
              i = 1; 
          } 
      } 
      
      class Sub extends Super
      {
          public Sub(String text)
          {
              i = 2; 
          } 
      
          public static void main(String args[])
          {
              Sub sub = new Sub("Hello"); 
              System.out.println(sub.i); 
          } 
      }
      

    • Options
    • A. 0
    • B. 1
    • C. 2
    • D. Compilation fails.
    • Discuss
    • 2. What will be the output of the program (in jdk1.6 or above)?
      public class BoolTest 
      {
          public static void main(String [] args) 
          {
              Boolean b1 = new Boolean("false");
              boolean b2;
              b2 = b1.booleanValue();
              if (!b2) 
              {
                  b2 = true;
                  System.out.print("x ");
              }
              if (b1 & b2) /* Line 13 */
              {
                  System.out.print("y ");
              }
              System.out.println("z");
          }
      }
      

    • Options
    • A. z
    • B. x z