Google Search

Wednesday, July 15, 2009

JAVA INTERVIEW QUESTION PART3



25.What is an abstract class?
Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation.
Note:
· If even a single method is abstract, the whole class must be declared abstract.
· Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods.
· You can’t mark a class as both abstract and final.

26.Can we instantiate an abstract class?
An abstract class can never be instantiated. Its sole purpose is to be extended (subclassed).
28.When should I use abstract classes and when should I use interfaces?
Use Interfaces when…
· You see that something in your design will change frequently.
· If various implementations only share method signatures then it is better to use Interfaces.
· you need some classes to use some methods which you don't want to be included in the class, then you go for the interface, which makes it easy to just implement and make use of the methods defined in the interface.
Use Abstract Class when…
· If various implementations are of the same kind and use common behavior or status then abstract class is better to use.
· When you want to provide a generalized form of abstraction and leave the implementation task with the inheriting subclass.
· Abstract classes are an excellent way to create planned inheritance hierarchies. They're also a good choice for nonleaf classes in class hierarchies.

29.When you declare a method as abstract, can other nonabstract methods access it?
Yes, other nonabstract methods can access a method that you declare as abstract.

30.Can there be an abstract class with no abstract methods in it?
Yes, there can be an abstract class without abstract methods.
31.What is Constructor?
· A constructor is a special method whose task is to initialize the object of its class.
· It is special because its name is the same as the class name.
· They do not have return types, not even void and therefore they cannot return values.
· They cannot be inherited, though a derived class can call the base class constructor.
· Constructor is invoked whenever an object of its associated class is created.

32.How does the Java default constructor be provided?
If a class defined by the code does not have any constructor, compiler will automatically provide one no-parameter-constructor (default-constructor) for the class in the byte code. The access modifier (public/private/etc.) of the default constructor is the same as the class itself.

33.Can constructor be inherited?
No, constructor cannot be inherited, though a derived class can call the base class constructor.