What is the result?

Given:

public class SampleClass {
public static void main(String[] args) {
SampleClass sc, scA, scB;
sc = new SampleClass();
scA = new SampleClassA();
scB = new SampleClassB();
System.out.println(“Hash is : ” +
sc.getHash() + “, ” + scA.getHash() + “, ” + scB.getHash()); }
public int getHash() {
return 111111;
}
}
class SampleClassA extends SampleClass {
public long getHash() {
return 44444444;
}
}
class SampleClassB extends SampleClass {
public long getHash() {
return 999999999;
}
}

What is the result?

Given:

public class SampleClass {
public static void main(String[] args) {
SampleClass sc, scA, scB;
sc = new SampleClass();
scA = new SampleClassA();
scB = new SampleClassB();
System.out.println(“Hash is : ” +
sc.getHash() + “, ” + scA.getHash() + “, ” + scB.getHash()); }
public int getHash() {
return 111111;
}
}
class SampleClassA extends SampleClass {
public long getHash() {
return 44444444;
}
}
class SampleClassB extends SampleClass {
public long getHash() {
return 999999999;
}
}

What is the result?

A.
Compilation fails

B.
An exception is thrown at runtime

C.
There is no result because this is not correct way to determine the hash code

D.
Hash is: 111111, 44444444, 999999999

Explanation:
The compilation fails as SampleClassA and SampleClassB cannot override SampleClass because the return type of SampleClass is int, while the return type of SampleClassA and SampleClassB is long.
Note: If all three classes had the same return type the output would be:
Hash is : 111111, 44444444, 999999999



Leave a Reply 2

Your email address will not be published. Required fields are marked *


Jazz

Jazz

A – Compile Time Error

Explaination:

public int getHash() {
return 111111;
}

Here the return type of getHash() is Long, but it is as int. So in-compatiable type Error.

If it is defined as

public long getHash() {
return 111111;
}

then output is : “D”

James

James

The Answer is A.

In order for the derived classes (SampleClassA and SampleClassB) to properly override the getHash() method of the base class (SampleClass), the same method signature must be used (i.e., the return type of the overridden methods must be int and not long for the code to successfully compile).