METHOD OVERRIDING & METHOD OVERLOADING

Question no -1 What is the output for the below code ?

public class B {
 
 public String getCountryName(){
  return "USA";
 }
 
 public StringBuffer getCountryName(){
  StringBuffer sb = new StringBuffer();
  sb.append("UK");
  return sb;
 }
 
 public static void main(String[] args){
  B b = new B();
  System.out.println(b.getCountryName().toString());
 }

}

A)Compile with error
B)USA
C)UK
D) Runtime Exception

Answer 1: A
You cannot have two methods in the same class with signatures that only differ by return type.

Question no -2 What is the output for the below code ?

public class C
{
}

public class D extends C
{
}

public class A {
 
 public C getOBJ(){
  System.out.println("class A - return C");
  return new C();
  
 }

}

public class B extends A{
 
 public D getOBJ(){
  System.out.println("class B - return D");
  return new D();
  
 }

}

public class Test {

public static void main(String... args) {
     A a = new B();
     a.getOBJ();
 
     }
}

A)Compile with error - Not allowed to override the return type of a method with a subtype of the original type.
B)class A - return C
C)class B - return D
D) Runtime Exception

Answer 2: C
From J2SE 5.0 onwards. You are now allowed to override the return type of a method with a subtype of the original type.

Question no -3 What is the output for the below code ?

public class A {
 
 public String getName() throws ArrayIndexOutOfBoundsException{
  return "Name-A";
 }
 
}
 
public class C extends A{
 
 public String getName() throws Exception{
  return "Name-C";
 }

}
 
 
public class Test {
 public static void main(String... args) {
  A a = new C();
  a.getName();
 }
 
}

A)Compile with error
B)Name-A
C)Name-C
D)Runtime Exception

Answer 3: A
 Exception is not compatible with throws clause in A.getName().
Overridden method should throw only same or sub class of the exception thrown by super class method.