A Technology Blog About Code Development, Architecture, Operating System, Hardware, Tips and Tutorials for Developers.

Tuesday, November 6, 2012

Java OOPS Interview Questions

5:24:00 PM Posted by Satish No comments
These are the questions I have drafted depending on my experience level. In order to be comfortable in OOPS concept, you need have a clear understanding of these concepts rather than mocking up these answers. Normally there used to be a heavy debate on these in interviews. I would appreciate to have cross questioning in these.

JAVA INTERVIEW QUESTION
                                             1. Java OOPS Interview Questions
                                             2. Core Java Interview Questions
                                             3. Java Serialization Interview Question
                                             4. Collection Framework Interview Question
                                             5. Java Multi-Threading Interview Question

What are the basic principles of OOPS?

There are three basic principles of Object Oriented Programming Structure (OOPS)
Polymorphism: Briefly described as "one interface, many implementations."
Inheritence: Process of Aquiring properties from one object to another without changes.
Encapsulation: Wrapping up of data and methods in to a single unit.
Abstraction: Abstraction is essential element of Object Oriented Programming. 

What is Encapsulation?

It is the mechanism that binds together code and data in manipulates and keeps both safe from outside interference and misuse. In short it isolates a particular code and data from all other codes and data. A well-defined interface controls the access to that particular code and data. In Java the basis of encapsulation is the class. A class defines the structure and behavior(data and code) that will be shared by a set of objects. Each object of a given class contains the structure and behavior defined by the class as if it were stamped out of a mold in the shape of a class. A class is a logical construct an object has physical reality. When you create a class you will specify the code and data that will constitute that class. Collectively these elements are called the members of the class. Specifically the data defined by the class are referred to as member variables or instance variables.The code that operates on that data is referred to as member methods or just methods which define the use of the member variables. 

Since the purpose of a class is to encapsulate complexity there are mechanisms for hiding the complexity of the implementation inside the class. Each method or variable in a class may be marked public or private. The private methods and data can only be accessed by the code that is a member of the class. The public method has all details essential for external users.

What is Inheritence?

It is the process by which one object acquires the properties of another object. This supports the hierarchical classification. Without the use of hierarchies each object would need to define all its characteristics explicitly. However by use of inheritance an object need only define those qualities that make it unique within its class. It can inherit its general attributes from its parent. A new sub-class inherits all of the attributes ofall of its ancestors.
  • A class that is inherited is called a superclass.
  • The class that does the inheriting is called a subclass.
  • Inheritance is done by using the keyword extends.
The two most common reasons to use inheritance are: 
  1. To promote code reuse 
  2. To use polymorphism
What is Polymorphism?

It is a feature that allows one interface to be used for general class of actions. The specific action is determined by the exact nature of the situation.In general polymorphism means one interface multiple methods .This means that it is possible to design a generic interface to a group of related activities. This helps reduce complexity by allowing the same interface to be used to specify a general class of action. It is the compiler's job to select the specific action (that is method) as it applies to each situation.

What is Abstraction?

Abstraction is an essential element of Object Oriented Programming which manages the complexity. In a sense, when someone works on a computer, its not necessary that person should know the working of each and every part of the computer. Even without the hardware knowledge he can e-mail, type or do any other job on the computer. Thus people do not think of a computer as a unit made up of hundreds of cards and chips but as a well-defined object with its own unique behavior. This is the advantage of abstraction. 

Object-oriented programming is modeled on how in the real world objects are often made up of many kinds of smaller objects. This capability of combining objects however is only one very general aspect of object-oriented programming.

How does Java implement polymorphism ?
(Inheritance, Overloading and Overriding are used to achieve Polymorphism in java). Polymorphism manifests itself in Java in the form of multiple methods having the same name.
  • In some cases, multiple methods have the same name, but different formal argument lists (overloaded methods).
  • In other cases, multiple methods have the same name, same return type, and same formal argument list (overridden methods).
Explain the different forms of Polymorphism.

There are two types of polymorphism one is Compile time polymorphism and the other is run time polymorphism. Compile time polymorphism is method overloading. Runtime time polymorphism is done using inheritance. 
Note: From a practical programming viewpoint, polymorphism manifests itself in two distinct forms in Java:
  • Method overloading
  • Method overriding through inheritance
What is the difference between abstraction and encapsulation ?
  • Abstraction focuses on the outside view of an object (i.e. the interface) Encapsulation (information hiding) prevents clients from seeing it's inside view, where the behavior of the abstraction is implemented.
  • Abstraction solves the problem in the design side while Encapsulation is the Implementation.
  • Encapsulation is the deliverables of Abstraction. Encapsulation barely talks about grouping up your abstraction to suit the developer needs.
How do you express an "is a" relationship and a "has a" relationship? Explain Inheritance and Composition?

The 'is a' relationship is expressed with inheritance and 'has a' relationship is expressed with composition. Both inheritance and composition allow you to place sub-objects inside your new class. Two of the main techniques for code reuse are class inheritance and object composition. 

Inheritance is uni-directional. For example House is a Building. But Building is not a House. Inheritance uses extends key word. Composition is used when House has a Bathroom. It is incorrect to say House is a Bathroom. Composition simply means using instance variables that refer to other objects. The class House will have an instance variable, which refers to a Bathroom object. 

Inheritance should be only used when subclass 'is a' superclass.
  • Don't use inheritance just to get code reuse. If there is no 'is a' relationship then use composition for code reuse. Overuse of inheritance (uses the "extends" key word) can break all the subclasses, if the superclass is modified.
  • Do not use inheritance just to get polymorphism. If there is no 'is a' relationship and all you want is polymorphism then use interface inheritance with composition, which gives you code reuse.

What is method Overriding ?

An method in a subclass with the same signature (name, plus the number and the type of its parameters) and return type as a method in the superclass, then the superclass's method is said to be overridden by the subclass method, or the subclass method overrides the superclass's method. 

Any time you have a class that inherits a method from a superclass, you have the opportunity to override the method, unless the method is marked final The key benefit of overriding is the ability to define behavior that's specific to a particular subclass type. 

The following example demonstrates a Horse subclass of Animal overriding the Animal version of the eat() method:

public class Animal {
 public void eat() {
 System.out.println("Generic Animal Eating Generically");
 }
}
  
class Horse extends Animal {
 public void eat() {
 System.out.println("Horse eating hay, oats, and horse treats");
 }
}

For abstract methods you inherit from a superclass, you have no choice. You must implement the method in the subclass unless the subclass is also abstract. So you could think of abstract methods as methods you're forced to override.

What are the rules for Overridding a method?

The rules for overriding a method are as follows:
  • The argument list must exactly match that of the overridden method. If they don't match, you can end up with an overloaded method you didn't intend.
  • The return type must be the same as, or a subtype of, the return type declared in the original overridden method in the superclass.
  • The access level can't be more restrictive than the overridden method's.
  • The access level CAN be less restrictive than that of the overridden method.
  • Instance methods can be overridden only if they are inherited by the subclass. A subclass within the same package as the instance's superclass can override any superclass method that is not marked private or final. A subclass in a different package can override only those non-final methods marked public or protected (since protected methods are inherited by the subclass).
  • The overriding method CAN throw any unchecked (runtime) exception, regardless of whether the overridden method declares the exception.
  • The overriding method must NOT throw checked exceptions that are new or broader than those declared by the overridden method. For example, a method that declares a FileNotFoundException cannot be overridden by a method that declares a SQLException, Exception, or any other non-runtime exception unless it's a subclass of FileNotFoundException.
  • The overriding method can throw narrower or fewer exceptions. Just because an overridden method "takes risks" doesn't mean that the overriding subclass exception takes the same risks. Bottom line: an overriding method doesn't have to declare any exceptions that it will never throw, regardless of what the overridden method declares.
  • You cannot override a method marked final.
  • You cannot override a method marked static.
  • If a method can't be inherited, you cannot override it. Remember that overriding implies that you're reimplementing a method you inherited.
What is the difference between Overriding and Hiding Methods?

Instance Methods: 

An instance method in a subclass with the same signature (name, plus the number and the type of its parameters) and return type as an instance method in the superclass overrides the superclass's method. 

Class Methods: 

If a subclass defines a class method with the same signature as a class method in the superclass, the method in the subclass hides the one in the superclass. 

The distinction between hiding and overriding has important implications. The version of the overridden method that gets invoked is the one in the subclass. The version of the hidden method that gets invoked depends on whether it is invoked from the superclass or the subclass. Let's look at an example that contains two classes. The first is Animal, which contains one instance method and one class method:

public class Animal {
 public static void testClassMethod() {
     System.out.println("The class method in Animal.");
 }
 public void testInstanceMethod() {
     System.out.println("The instance method in Animal.");
 }
} 

The second class, a subclass of Animal, is called Cat:

public class Cat extends Animal {
 public static void testClassMethod() {
    System.out.println("The class method in Cat.");
 }
 public void testInstanceMethod() {
    System.out.println("The instance method in Cat.");
 }
 
 public static void main(String[] args) {
    Cat myCat = new Cat();
    Animal myAnimal = myCat;
    Animal.testClassMethod();
    myAnimal.testInstanceMethod();
 }
}

The Cat class overrides the instance method in Animal and hides the class method in Animal. The main method in this class creates an instance of Cat and calls testClassMethod() on the class and testInstanceMethod() on the instance. 

The output from this program is as follows: 

The class method in Animal.
The instance method in Cat.

So, the version of the hidden method that gets invoked is the one in the superclass, and the version of the overridden method that gets invoked is the one in the subclass.

Can we change the return type in the Overriding method?

As of Java 5, you're allowed to change the return type in the overriding method as long as the new return type is a subtype of the declared return type of the overridden (superclass) method.

class Alpha {
 Alpha doSomething(char c) {
     return new Alpha();
 }
}
  
class Beta extends Alpha {
 Beta doSomething(char c) { // legal override in Java 1.5
     return new Beta();
 }
}

As of Java 5, this code will compile. If you were to attempt to compile this code with a 1.4 compiler will throw error "attempting to use incompatible return type"

What are the Rules for Constructors?
  • Constructors can use any access modifier, including private. (A private constructor means only code within the class itself can instantiate an object of that type, so if the private constructor class wants to allow an instance of the class to be used, the class must provide a static method or variable that allows access to an instance created from within the class.)
  • The constructor name must match the name of the class.
  • Constructors must not have a return type.
  • It's legal (but stupid) to have a method with the same name as the class, but that doesn't make it a constructor. If you see a return type, it's a method rather than a constructor. In fact, you could have both a method and a constructor with the same name - the name of the class - in the same class, and that's not a problem for Java.
  • If you don't type a constructor into your class code, a default constructor will be automatically generated by the compiler.
  • The default constructor is ALWAYS a no-arg constructor.
  • If you want a no-arg constructor and you've typed any other constructor(s) into your class code, the compiler won't provide the no-arg constructor (or any other constructor) for you. In other words, if you've typed in a constructor with arguments, you won't have a no-arg constructor unless you type it in yourself.
  • Every constructor has, as its first statement, either a call to an overloaded constructor (this()) or a call to the superclass constructor (super()), although remember that this call can be inserted by the compiler.
  • If you do type in a constructor (as opposed to relying on the compiler-generated default constructor), and you do not type in the call to super() or a call to this(), the compiler will insert a no-arg call to super() for you, as the very first statement in the constructor.
  • A call to super() can be either a no-arg call or can include arguments passed to the super constructor.
  • A no-arg constructor is not necessarily the default (i.e., compiler-supplied) constructor, although the default constructor is always a no-arg constructor. The default constructor is the one the compiler provides! While the default constructor is always a no-arg constructor, you're free to put in your own noarg constructor.
  • You cannot make a call to an instance method, or access an instance variable, until after the super constructor runs.
  • Only static variables and methods can be accessed as part of the call to super() or this(). (Example: super(Animal.NAME) is OK, because NAME is declared as a static variable.)
  • Abstract classes have constructors, and those constructors are always called when a concrete subclass is instantiated.
  • Interfaces do not have constructors. Interfaces are not part of an object's inheritance tree.
  • The only way a constructor can be invoked is from within another constructor.
What is Coupling and Cohesion?

Coupling: Coupling is the degree to which one class knows about another class. If the only knowledge that class A has about class B, is what class B has exposed through its interface, then class A and class B are said to be loosely coupled?that's a good thing. If, on the other hand, class A relies on parts of class B that are not part of class B's interface, then the coupling between the classes is tighter?not a good thing. In other words, if A knows more than it should about the way in which B was implemented, then A and B are tightly coupled. 

Cohesion: While coupling has to do with how classes interact with each other, cohesion is all about how a single class is designed. The term cohesion is used to indicate the degree to which a class has a single, well-focused purpose. The more focused a class is, the higher its cohesiveness - a good thing. The key benefit of high cohesion is that such classes are typically much easier to maintain (and less frequently changed) than classes with low cohesion. Another benefit of high cohesion is that classes with a well-focused purpose tend to be more reusable than other classes.

0 comments:

Post a Comment