Object -Interview Questions

Object concepts

Q: What is an object in Java?

A: In Java the Object class is the ultimate superclass of every other object type. All objects are extended from the Object class, either directly or by inheritance through any number of parent classes. If a class does not explicitly extend any named class, it implicitly extends the Object class. An object with a small o is the word used to describe an instance of a Java class.



Q: What's the difference between a class and an object in Java?

A: A Java class is a definition or model of an object type. A class has a specific set of fields, methods and constructors with distinct argument types. Any object that fulfills a class definition directly or by inheritance has a set of properties and behaviour that is common to all instances of the class. In this sense, a class is a set of things that are alike.

In Java concrete classes also provide a code implementation that can be instantiated to create an object reference. An instance of a class directly fulfills its own definition, it also fulfills any superclass definitions too.

The Java Virtual Machine creates static references to classes when it runs a Java program. Classloaders make the public static fields and methods of classes available to the runtime system whether any instance exists or not. When a constructor is called, the class returns an instance of the object it represents.

Q: What's the difference between an instance and an object?

A: When you create a Java object by calling its constructor, the object reference that is returned is called an instance. This means there is little difference between the two terms. The word instance is usually used when we talk about the process of object creation or instantiation, it is a single reference to an object. The word object can also be used to talk collectively about the general properties and behaviour of a Java object.

Q: What is a concrete object?

A: The term concrete class is used to describe a class that can be instantiated to form an object instance in the Java Runtime Environment (JRE). A concrete object would be an instance of a concrete class and makes better sense in contrast with abstract classes and interfaces, which cannot be instantiated in their own right, only by extension or implementation by a concrete class.

Q: Which is the object in test t1 = new test()?

A: In this example the variable t1 holds a reference to an object of the class test, which is also known as an instance of the class test.

Understanding constructors

Q: What is a constructor?

A: A constructor is a special class method that is used to create an instance of the class. A constructor method is named after the class it belongs to and may have arguments. The constructor returns an instance of the class, which is an object you can use in your Java program.

The constructor is called without referring to an instance of the class. When you use the new keyword followed by the name of the class with parentheses, the Java compiler knows this is a constructor call for the class. The class instance it returns is normally assigned to a variable with an appopriate type, as below. You can call the constructor as many times as you like and it should always return an instance.

Object objectInstance = new Object();

 

Q: What is the difference between a constructor and an object?

A: A constructor is a special type of method that you use to create an instance of a class. An object is another name for an instance of a class. If you think of a Java source file as a plan or design for a component in a larger machine, when you call a class constructor it is like an instruction to the Java runtime system to say "make one of these". The runtime system returns an object based on that design which you can use in your Java program. You can call a constructor as many times as you want to get multiple instances of an object, which each exist independently but can also have linked behaviour and properties.

The Java statements in a constructor are intended to prepare a new object for the work it will do in a Java program. The constructor should ensure that the object has all necessary input arguments, configure itself for use and set up any linkages and dependencies with other Java objects.

Q: What is the difference between a method and a constructor?

A: Methods and constructors are quite similar in nature, you can think of a constructor as a special type of static method that implicitly returns an instance of the relevant class. Methods have an explicit return type in their signature that tells you what type of object or primitive the method will return, or void if none. A constructor has no explicit return type because it always returns an instance of the class. In most other ways constructors are like methods, they have the same visibility modifiers and may have zero, one or more arguments.

One notable property of constructors is that the Java compiler will automatically insert a call to the no-argument superclass constructor unless you explicitly add a superclass constructor statement. This arrangement will create a compilation error if the superclass does not have a visible no-argument constructor, in which case you must make the superclass constructor visible or add call to an alternative superclass constructor.

public class Example extends Superclass {



  public Example() {



    // Implicitly calls the superclass constructor Superclass()

  }



  public Example(final int param) {



    // Supersedes implicit call to superclass constructor

    super(param);

  }

}

 

Q: How do I invoke a constructor?

A: Java object constructors are invoked by putting the new operator before the class name and enclosing any constructor argument references in parentheses after it. A fundamental case is the Object class, which is invoked as follows.

Q: How can I call a constructor from a constructor?

A: When you have a number of constructors in a class you can call them using this() in a similar way to the superclass constructor super(). For instance, if you have a "good citizen" constructor that takes a Stringand a boolean, and a shorthand version that only takes a String, you may pass a default value to the two argument constructor, as below.

Q: Is it OK to tag inline method calls on constructors?

A: Using a dot separator to call a method on a new instance is a convenience technique that combines two statements in one. There is no practical difference in the method invocation, in both cases a new instance is created and the method is executed, but in practice the code can create unnecessary anonymous instances and confuse the assignment of the return value. For clarity it is better to use two separate statements with obvious assignments, as the series of examples below illustrate.

Q: What does the statement super($anonymous0) mean in Java?

A: The statement super($anonymous0) would be used as the first statement of a class constructor, it passes the variable $anonymous0 to the superclass constructor. It may be necessary to store or read configuration details from the variable to properly prepare the class for use, for example. That means that the superclass must have a constructor with a single argument that matches the type of the variable$anonymous0. The variable $anonymous0 must be passed as an argument to the subclass constructor or be a static variable of the subclass because its reference must be defined before the superclass constructor is called.

Q: Why do we use static initializer blocks?

A: Static initializer blocks tend to be used in classes that have important properties and behaviour that are accessed in a static context and may require some runtime configuration. A static initializer block is similar in nature to a class constructor, except it is executed when the class is first loaded by the Java runtime system, before any instance is created. Static initialization blocks may set the initial value of static variables using relatively complex logic, execute Java statements and call other methods. Since this code runs before any instance of the host class exists, it cannot work with instance variables or methods of its own.

Static initializer blocks enable programmers to run relatively complex code during class loading to prepare a class for use in a purely static context, or when it would be "too late" to run the code in a constructor call.

static {



  // Execute statements during class loading

}

 

Object design

Q: How can I count the number of instances of an object?

A: To count all instances of a class you should create a static int variable to store the number of instances and include an increment statement in all constructors. You must also implement a final finalize()method that is called upon garbage collection to decrement the count. And since multiple instances may increment and decrement the static value in separate threads, these statements should be enclosed in asynchronized block, as in the example below.

Q: Can objects be used in place of arrays?

A: Yes, sometimes it is sensible to use an object to carry other object references instead of an array. For instance, you could issue an object as the return value of a method that must return multiple object references.

Q: What's the difference between equals and ==?

A: The Java == operator is used to compare primitive values such as int, long and boolean for equality; whether the variables, values or expression on either side of the operator equate to the same value.

Object methods

Q: Can I use the same variable name in two methods?

A: It is possible to use the same variable names for method local variables in two separate methods, and in separate statement blocks, enclosed by curly braces, { and }. Methods and statement blocks have their own variable scope, so the Java compiler and interpreter can maintain a distinction between the variables they contain. Generally it is preferable for variables that represent different properties to have different names to avoid confusion, but it is likely that several methods may use an index named i in a for loop for example.

public class MethodLocalVariables {



    void testOne() {



        int test;

    }



    void testTwo() {



        int test;

    }

}

   

Q: Is it possible to use the same variable name in the same method?

A: It is technically possible to use the same variable name in separate statement blocks because the variables are localised; the compiler can deduce from their context that they are different things, see the working example below. However, it is not advisable to use the same variable name in multiple places, especially within the same method, because it is confusing and can lead to bugs.

public class RepeatLocalVariables {



  public final void doSomething(final String thing) {



    if ("thing one".equals(thing)) {



      int a;

      // Other statements

    }

    if ("thing two".equals(thing)) {



      int a;

      // Other statements

    }

  }

}

   

If both variables in this example are actually used for the same purpose, a single variable declaration should be made in the main body of the method. If the variables are for different purposes, it would be better to name them differently.

Q: What is the syntax for methods with no argument?

A: The syntax for methods with no arguments is to follow the method name with open and close brackets with nothing in between. This syntax applies to static and instance methods, and those with void, primitive or object return types.

public final void noArguments() {



  // Method statements

}

   

Q: How can I get the caller of a method?

A: In most cases it is not relevant or necessary for a Java method to know the object that called it. If your code needs to know the origin of a method call it is likely the method is located in the wrong host class, or your overall program structure does not follow good object oriented principles. Consider whether you can move the method to a different host class or refactor to place class-specific code in the relevant classes.

If you find there really is good reason to know the origin of method calls, add an Object argument to the method and use the getClass() method to test.

Q: How does an object call an inner class method?

A: Host classes call methods on inner classes in exactly the same way as they would on a separate class defined in its own compilation unit. To call an inner class' instance method it is necessary to instantiate the class first, as below.

Q: What is the difference between a method header and its signature?

A: A Java method header is the whole declaration statement for a method before its curly braces. The header includes the method's visibility modifier, return type, arguments and exceptions, as below.

public final String getDetails(final File file,

                               final String key) throws IOException

   

A Java method signature is the method name and parameters only. The order of the parameters is significant because they may distinguish overloaded methods by the same name.

getDetails(File, String)

   

Object comparison methods

Q: When is hashCode() used?

A: The hashCode() method is used in hash-based data stores to get a "nearly unique" identifier for each object. The hash code is used to speed up the search process, so should have a high probability of being different from any other instance. It is possible for two hash codes to be the same, so the equals method is used to make an exact match.

Q: How can I create a constructor to equate two other objects?

A: Normally when we compare two objects we use the fundamental equals(Object) method. Conceptually, the equals method "belongs" to the objects you are comparing and returns a boolean to indicate whether they are passed a reference to themselves.

Its not obvious why you would choose to make that comparison in the constructor of another class, which may only return a reference to the new instance, not a simple boolean response. In any case, the example below shows how you can compare method arguments and return a boolean, which could be refactored for use in a constructor.