Overriding And Overloading - Study Mode

[#41] What will be the output of the following program code? class Rectangle{
public int area(int length, int width){
return length*width
}
}
class Square extends Rectangle{
public int area(long length, long width){
return (int) Math.pow(length, 2)
}
}
public class Test{
public static void main(String args[]){
Square r = new Square()
System.out.println(r.area(5 , 4))
}
}
Correct Answer

(B) Will compile and run printing out 20

[#42] What will be printed after executing following program code? class Base{
int value = 0
Base(){
addValue()
}
void addValue(){
value += 10
}
int getValue(){
return value
}
}
class Derived extends Base{
Derived(){
addValue()
}
void addValue(){
value += 20
}
}
public class Test{
public static void main(String[] args){
Base b = new Derived()
System.out.println(b.getValue())
}
}
Correct Answer

(D) 40

[#43] What will be the output? class A{
static void method(){
System.out.println("Class A method")
}
}
class B extends A{
static void method(){
System.out.println("Class B method")
}
}
public class Test{
public static void main(String args[]){
A a = new B()
a.method()
}
}
Correct Answer

(A) Class A method

Explanation

Solution: Overriding in Java simply means that the particular method would be called based on the run time type of the object and not on the compile time type. But in the above case the methods are static which means access to them is always resolved during compile time only using the compile time type information. Accessing them using object references is just an extra liberty given by the designers of Java.

[#44] What will be the output? class A{
int i = 10
public void printValue(){
System.out.print("Value-A")
}
}
class B extends A{
int i = 12
public void printValue(){
System.out.print("Value-B")
}
}
public class Test{
public static void main(String args[]){
A a = new B()
a.printValue()
System.out.print(a.i)
}
}
Correct Answer

(B) Value-B 10

Explanation

Solution: If you create object of subclass with reference of super class like ( A a = new B()
) then subclass method and super class variable will be executed.

[#45] What is the output for the below code? public class Test{
public static void printValue(int i, int j, int k){
System.out.println("int")
}
public static void printValue(byte...b){
System.out.println("long")
}
public static void main(String... args){
byte b = 9
printValue(b,b,b)
}
}
Correct Answer

(B) int

Explanation

Solution: Primitive widening uses the smallest method argument possible. (For Example if you pass short value to a method but method with short argument is not available then compiler choose method with int argument). But in this case compiler will prefer the older style before it chooses the newer style, to keep existing code more robust. var-args method is looser than widen.