Tech
Java Question and Points to Remember
Below are few of Java questions that i came across when learning Java.
- A reference variable can be declared as a class type or an interface type. If declared as a class type, the objects that it references can be of that class type or of any of its sub class types. If the reference is an interface, the object can be any class that implements that interface. Can it be a subclass of a class that implements that interface?
- Can there be more than one public class in the same java file?
- Will the below code compile and run succesfully ?
byte g = 2;
switch(g) {
case 23: System.out.println(“Hello”);
case 128: System.out.println(“Hello”);
}
Ans: No Gives compilation error at case 128: Compiler expects the case values to be of same data type as that of the case variable, in this case a byte. But 128 is too big for a byte. When it tries to compare 128 to byte compiler complains possible loss of precision
POINTS TO REMEMBER
- If a class extends two classes it is called multiple inheritance. This is not allowed in Java.
- When overriding a base class method in a sub class the subclass cannot give the method a lesser access than the base class. For Example, if the base class has a method marked protected, the subclass cannot override it as private. It can override it as protected or public.
- Overriding is changing the body of the method in the subclass when it inherits a method from the base class.
- The return type of the overloaded method should be the same as in the base class or of a subclass type of the return type declared in the base class.
- Overloading is changing the parameters keeping the same name for the method. In overloading method names are the same but differ in parameters (return type doesn’t matter). Overloading takes place in the same class.
- The overriding method can throw unchecked runtime exceptions irrespective of if the base class method threw any exception.
- If the base class method declares exception the subclass method should throw an exception which is a subtype of that exception. It need not throw any exception just because the base class method throws exception.
- You cannot override a method marked static or final.
- You cannot override a method which was not inherited.




