Saturday, 6 April 2013

MCQ #11

Question) Are you allowed to have more than one top level (non inner) class definition per source file?


  • No
  • Yes
Answer) Yes

Explanation) Yes you can have multiple top level class definitions per source file. Yeah, it's also true that the source file name must be same as that of the class name. To resolve both these constraints Java states some basic rules which are -
  1. Out of the multiple top level classes defined only one can be public.
  2. Source file name must match this public class name.

Interview Question #7 What is final in java?

A final class can't be extended ie., final class may not be subclassed. A final method can't be overridden when its class is inherited. You can't change value of a final variable (is a constant).

If you want a variable to be owned by the class and not by it's individual instances(objects) and also you want the value of the variable to be constant you can declare it as static and final both.

 For Example
       private final static String name = "JavaForGeeks";

The concept is interpreted a bit different way for Objects, Collections. You can change the data inside the object/Collection but cannot make the reference(which is final) point to different Object.

For example

public class HelloWorld {
    String greetings;
    public String getGreetings() {
        return greetings;
    public void setGreetings(String greetings) {
        this.greetings = greetings;


Even if the HellowWorld instance is defined final you can call setter method of it's data.

    public static void main(String args[]){
        final HelloWorld hw = new HelloWorld();
        hw.setGreetings("test");  //allowed
        //hw = new HelloWorld(); //not allowed

Same goes for Collections

    public static void main(String args[]){
        final List<String> myList = new ArrayList<String>();
        myList.add("Test");    //allowed
        //myList = new ArrayList<String>();    //not allowed


Interview Question #6 What is static in java?

Static means one per class, not one for each object no matter how many instance of a class might exist. This means that you can use them without creating an instance of a class.Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object. A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can't override a static method with a nonstatic method. In other words, you can't change a static method into an instance method in a subclass.

For more details refer the tutorial on Static keyword in Java.
t> UA-39527780-1 back to top