You are on page 1of 36

1)Explain abstract class in Java.

Ans:- in java as soon as u define a class with


"abstract" keyword, class becomes abstract.
abstract class cannot be instantiated.
abstract class can contain abstract as well as non-
abstract methods.
abstract method is a method which is declared with
"abstract" keyword.
a child class of an abstract class has to provide
implementation to the method which is declared
"abstract" in parent class or else make child class
also "abstract".

2)What is the need of abstract class?


Ans:- Abstract classes let you define some behaviors;
they force your subclasses to provide others. For
example, if you have an application framework, an
abstract class may provide default services (concrete)
such as event and message handling. Those services
allow your application to plug in to your application
framework. However, there is some application-specific
functionality (abstract) that only your application can
perform. Such functionality might include startup and
shutdown tasks, which are often application-dependent.
So instead of trying to define that behavior itself, the
abstract base class can declare abstract shutdown and
startup methods. The base class knows that it needs
those methods, but an abstract class lets your class admit
that it doesn't know how to perform those actions; it
only knows that it must initiate the actions. When it is
time to start up, the abstract class can call the startup
method. When the base class calls this method, Java calls
the method defined by the child class.

3)Explain interface in Java8


Ans:- interfaces are abstract in nature. i.e. they can
not be instantiated.

interface can contain


members
abstract methods
default methods
static methods
members declared in interface are by default
"public","static" and "final".

methods declared ( and not defined) inside interface


are by default "public" and "abstract".

a class can be derived from more than one


interfaces. (implements keyword is used here )

child class of an interface has to provide


implementation of the method/s which are declared
abstract in parent or else child class also has to be
declared as "abstract".

default method/s (which are by default "public")


may or may not be overridden by child class. ( if
overridden, "public" modifier is compulsory)

static methods are like utility methods which can be


invoked only on the interface in which they are
defined.
4)Why do we need interface?
Ans:- Interfaces are important because they separate
what a class does from how it does it. The contract
defining what a client can expect leaves the developer
free to implement it any way they choose, as long as they
uphold the contract.
You see examples of this all over the JDK. Look at the
java.sql package - it's riddled with interfaces. Why? So
different relational databases can be free to implement
those methods for their particular product. Clients need
only deal with the interface reference types. Changing
relational databases is as easy as swapping one JDBC
driver JAR for another. Clients need not change. (As long
as they don't stray from the contract.)
You can program to an interface instead of a concrete
implementation in order to make your code flexible.
In addition to this, interfaces make unrelated classes
relate e.g.

class Aeroplane extends Vehicle{}


class SuperMan extends Person{}
class Bird extends Animal{}
Though these classes are unique, there exists one
common factor “fly()”
So we can relate these unrelated classes with the
interface “Flyable”
interface Flyable
{
void fly();
}

class AeroPlane extends Vehicle implements


Flyable{public void fly(){ fly like AeroPlane}}
class SuperMan extends Person implements
Flyable{public void fly(){ fly like SuperMan}}
class Bird extends Animal implements Flyable{public void
fly(){ fly like Bird}}

And now somewhere we can have code :


void perform(Flyable ref)
{
ref.fly();
}
And we can pass :
perform(new AeroPlane());
perform(new SuperMan());
perform(new Bird());

5) Using interface reference we can invoke only those


methods which are present in it.
Given:

interface myinterface
{
void disp();
}
public class MyClass
{
public static void main(String[] args)
{
myinterface m1,m2=null;
m1.disp();
m1.fun();
m1.toString();
m1.equals(m2);
m1.hashCode();
}
}

Which of the above invocations are


illegal at compile-time?
Ans:- only “m1.fun();” is illegal, rest
all are legal at compile-time. It is
true that using interface reference we can
invoke only those methods which are present in it.
But “toString()” ,”equals()” and “hashCode()”
invocations are legal because these methods are
available inside “java.lang.Object” which is the base
class of all the classes in java. Now compiler
understands that any implementation of given
interface is by default sub class of “java.lang.Object”,
hence compiler allows you to invoke above
mentioned methods using interface reference.

6)When to use interface and when to use abstract


class? Explain with example.

Interface is used when you want to define a


contract and you don't know anything about
implementation. (here it is total abstraction as
you don't know anything.)

Abstract class is used when you know something


and rely on others for what you don't know.(here it
is partial abstraction as some of the things you
know and some you don't know.)

When to use Interface


Scenario, 
Consider we want to start a service like
"makemytrip.com" or "expedia.com", where we are
responsible for displaying the flights from various
flight service company and place an order from
customer. 
Let’s keep our service as simple as, 
1.Displaying flights available from vendors like
"airasia", "british airways" and "emirates".
2.Place and order for seat to respective vendor.

How should we design our application


considering interfaces and abstract class? In this
scenario, interface is useful or abstract class?

Remember, In this application, we don't own any


flight. we are just a middle man/aggregator and
our task is to first enquire "airasia", then enquire
"british airways" and at last enquire "emirates"
about the list of flights available and later if
customer opts for booking then inform the
respective flight vendor to do booking.

For this, first we need to tell "airasia", "british


airways" and "emirates" to give us list of flights,
internally how they are giving the list that we don't
care.
1.This means I only care for method
"getAllAvailableFlights()"
"getAllAvailableFlights()" from "airasia" may
have used SOAP service to return list of flights.
"getAllAvailableFlights()" from "british air-
ways" may have used REST service to return list
of flights.
"getAllAvailableFlights()" from "emirates" may
have used CORBA service to return list of
flights.

but we don't care how it is internally imple-


mented and what we care is the contract
method "getAllAvailableFlights" that all the
flight vendor should provide and return list of
flights.

2.Similarly, for booking I only care for method


"booking()" that all vendors should have, inter-
nally how this vendors are doing booking that I
don't care.

To conclude: We know contract. 


So we can say that we know the contract that
irrespective of who the Flight vendor is, we need
"getAllAvailableFlights()" and "booking()" method
from them to run our aggregator service.
In this situation, Interface is useful because we are
not aware of the implementation of all the 2
methods required, and what we know is the
contract methods that vendor(implementer) should
provide. so due to this total abstraction and for
defining the contract, interface is useful in this
place.
Technically, we need to design our interface
somewhat like below,

FlightOpeartions.java(Contract) 
?
1 interface FlightOpeartions{
2  void getAllAvailableFlights();
3  void booking(BookingObject bookingObj);
4 }
BookingObject.java 
?
1 class BookingObject{}
BritishAirways.java (Vendor 1) 
?
1 class BritishAirways implements
2 FlightOpeartions{
3  
4  public void getAllAvailableFlights(){
5            //get british airways flights
6 in the way
           //they told us to fetch
flight details.
 }
7  
8  public void booking(BookingObject
9 flightDetails){ 
10           //place booking order in a way
11 British airways
12           //told us to place order for
13 seat.
 }
 
}
Emirates.java (Vendor 2) 
?
1 class Emirates implements
2 FlightOpeartions{
3  
4  public void getAllAvailableFlights(){
5          //get Emirates flights in the
6 way
7          //they told us to fetch flight
8 details.
9  }
10  
11  public void booking(BookingObject
12 flightDetails){ 
         //place booking order in a way
Emirates airways
         //told us to place order for
seat.
 }
}

When to use Abstract class


Scenario, 
Consider we want to start a service like Bulk SMS
sender, where we take orders from various
telecom vendors like Airtel, France Telecom,
Vodafone etc.

For this, we don't have to setup our own


infrastructure for sending SMS like Mobile towers
but we need to take care of government rules like
after 9PM, we should not send promotional SMS, we
should also not send SMS to users registered under
Do Not Disturb(DND) service etc. Remember, we
need to take care of government rules for all the
countries where we are sending SMS.

Note: for infrastructure like towers, we will be


relying on vendor who is going to give us order.
Example, In case of,
Vodafone request us for bulk messaging, in that
case we will use Vodafone towers to send SMS. 
Airtel request us for bulk messaging, in that case
we will use Airtel towers to send SMS.
What our job is to manage Telecom Regulations for
different countries where we are sending SMS. 
  
So what all methods we require would be
somewhat like below,
?
1 public void
2 eastablishConnectionWithYourTower(){
3    //connect using vendor way.
4    //we don't know how, candidate for
5 abstract method
6 }
7  
8 public void sendSMS(){
9    eastablishConnectionWithYourTower();
10    checkForDND();
11    checkForTelecomRules(); 
12    //sending SMS to numbers...numbers.
13    destroyConnectionWithYourTower()
14 }
15  
16 public void
17 destroyConnectionWithYourTower(){
18    //disconnect using vendor way.
19    //we don't know how, candidate for
20 abstract method
}
 
21
public void checkForDND(){
22    //check for number present in DND.
23 }
24
 
25 public void checkForTelecomRules(){
26    //Check for telecom rules.
}

Out of above 5 methods, 


1.Methods we know is "sendSMS()", "check-
ForDND()", "checkForTelecomRules()".
2.Methods we don't know is "eastablishConnec-
tionWithYourTower()", "destroyConnectionWith-
YourTower()".
we know how to check government rules for
sending SMS as that is what our job is but
we don't how to eastablish connection with tower
and how to destroy connection with tower because
this is purely customer specific, airtel has its own
way, vodafone has its own way etc. 

So in the given scenario, we know some methods


but there also exist some methods which are
unknown and depends on customers.
In this case, what will be helpful, abstarct class or
interface?

In this case, Abstract class will be helpful,


because you know partial things like
"checkForDND()", "checkForTelecomRules()" for
sending sms to users but we don't know how to
eastablishConnectionWithTower() and
destroyConnectionWithTower() and need to
depend on vendor specific way to connect and
destroy connection from their towers.
Let's see how our class will look like,
?
1 abstract class SMSSender{
2   
3  abstract public void
4 eastablishConnectionWithYourTower();
5   
6  public void sendSMS(){
7   /*eastablishConnectionWithYourTower();
8   checkForDND();
9   checkForTelecomRules(); 
10    
11   sending SMS to numbers...numbers.*/
12  }
13  
14  abstract public void
15 destroyConnectionWithYourTower();
16  
17  public void checkForDND(){
18   //check for number present in DND.
19  }
20  public void checkForTelecomRules(){
21   //Check for telecom rules
22  }
23 }
24  
25  
26 class Vodafone extends SMSSender{
27  
28  @Override
29  public void
30 eastablishConnectionWithYourTower() {
31   //connecting using Vodafone way
32  }
33  
34  @Override
35  public void
36 destroyConnectionWithYourTower() {
37   //destroying connection using Vodafone
38 way
39  }
40   
41 }
42  
class Airtel extends SMSSender{
 
 @Override
 public void
43 eastablishConnectionWithYourTower() {
44   //connecting using Airtel way
45  }
46  
47  @Override
48  public void
49 destroyConnectionWithYourTower() {
50   //destroying connection using Airtel
way
 }
  
}

So to summarize, 
For Interface:
Interface is used when you don't know anything
about implementation but know the contract that
implementer should have to accomplish the task.
For Abstract class:
Abstract class is used when you know partial
implementation, where say out of 5 methods, you
know implementation of 3 methods and don't know
implementation of 2 methods in that case 2
methods will be abstract and you need to rely on
implementer as a contract to must provide body of
abstract methods to accomplish the task.
7)How many ways we can achieve Polymorphism in
Java?
Ans:-
Polymorphism using class
Class Animal
{
Int legs;
Virtual Void makeSound()
{
Cout<<”Groul”;
}
}
Class Cat extends Animal
{
Void makeSound()
{
Cout<<”meow…”;
}
}

Animal a=new Cat();


a.makeSound();

Polymorphism using interface.


e.g. how to relate unrelated classes
we have 3 objects from unrelated classes.

Vehicle IFlying - interface


Plane fly() - method
Superhero
Superman

Animal
Bird

IFlying f=list.nextObj();

Here list contains all “Plane” or “Bird” or


“Superhero” objects.

f.fly(); // late binding

this is polymorphism without using base class. i.e.


using base interface.
So , with the help of “IFlying” interface, we have
related all unrelated classes.
U can implement Polymorphism through Common
Interface among unrelated classes.

Apply interface when u don’t have common base


class.
Apply base class when u have related classes.

8) What is the difference between abstract class and


interface in Java8?

Ans:- Abstract class can define constructor.


They can have a state (instance members) associated with
them.
Interfaces still can't have any state. Interfaces still can't
have any final method, which means that any
implementation can override all its default methods. And
interfaces still can't have any constructor.
You can still implement multiple interfaces, even if they
have default methods with the same signature. You can't
extend multiple classes (abstract or not).
1. a class may inherit from only one other class, but can
implement many interfaces.
2. an interface may not have any fields, except defining
constants, while an abstract class can.
3. an abstract class may define a constructor, while an
interface cannot.
Default methods are restricted to input parameters and
method calls. They are stateless in nature. An abstract
class may have state. Hence, from the perspective of
design, we should use abstract classes whenever you need
code reuse.
Interfaces are perfect to follow the principle “Program to
interface and not implementation”.
9)What are the default methods in Java8 interfaces
Ans:- Java 8 introduces “Default Method” or
(Defender methods) or virtual extension methods new
feature, which allows developer to add new methods to
the interfaces without breaking the existing
implementation of these interface. It provides
flexibility to allow interface define
implementation which will use as default in the
situation where a concrete class fails to provide an
implementation for that method.
So now existing interfaces can be enhanced without
compromising backward compatibility by adding
extension methods to the interface, whose declaration
would contain instructions for finding the default
implementation in the event that implementers do not
provide a method body. A key characteristic of extension
methods is that they are virtual methods just like other
interface methods, but provide a default implementation
in the event that the implementing class does not provide
a method body.
10) What is the actual use of “default” method in
interface?

Ans:- if we want to add additional methods in the


interfaces, it will require change in all the implementing
classes. As interface grows old, the number of classes
implementing it might grow to an extent that it’s not
possible to extend interfaces. That’s why when designing
an application, most of the frameworks provide a base
implementation class and then we extend it and override
methods that are applicable for our application.
E.g. List is a parent interface for AbstractList abstract
class which is a parent for ArrayList,LinkedList etc.
interfaces are too tightly coupled with their
implementation classes. i.e. it is not possible to add
a method in interface without breaking the
implementer class. Once you add a method in
interface, all its implemented classes must declare
method body of this new method.

Java 8 introduces “Default Method” or (Defender


methods) or virtual extension methods new feature,
which allows developer to add new methods to
the interfaces without breaking the existing
implementation of these interface. It provides
flexibility to allow interface define implementation
which will use as default in the situation where a
concrete class fails to provide an implementation for
that method.
11) What do u mean by “Class wins” rule in java8?
Ans:- e.g. class C extends A implements B
Now class A has a concrete method “void disp()” and
interface B has a default method “void disp()”. In this
case C will inherit the method from class A and
default method from interface B will be simply be
ignored. This is the “Class wins” rule in java8. The
“Class wins” rule ensures compatibility with Java7.
12) Why it is not recommended to make a default
method that redefines one of the methods from
Object class?
Ans:- as a consequences of the “Class wins” rule
such method could never win against
Object.toString() or Object.equals().

13) Why do we need static methods in interface?


Ans:- static methods are the utility methods. Before
Java8,it has been common to place static methods in
companion classes.
You find pairs of interfaces and utility classes such as
Collection/Collections or Path/Paths in the standard
library. With the introduction of static methods now we
don’t require such utility classes.

14) Explain this vs super in case of constructor


invocation.
Ans:- this is used to invoke the constructors of same
class ( constructor chaining ) whereas super is used
to invoke parent class constructor.

15) What is equals and hashcode contract?


Ans:- a) Whenever it is invoked on the same
object more than once during an execution of a
Java application, the hashCode method must
consistently return the same integer, provided
no information used in equals comparisons on
the object is modified. This integer need not
remain consistent from one execution of an
application to another execution of the same
application.

b) If two objects are equal according to the


equals(Object) method, then calling the
hashCode method on each of the two objects
must produce the same integer result.
c) It’s not required that if two objects are unequal
according to the equals(java.lang.Object)
method, then calling the hashCode method on
each of the two objects must produce distinct
integer results. However, the programmer
should be aware that producing distinct integer
results for unequal objects may improve the
performance of hashtables.

16) What is the difference between == and equals()


method ?
Ans:- by default both of these are same i.e. both of
them check whether two references are referring to
same instance or not. If yes result is true otherwise
false. This is because in Object class equals() method
internally uses == operator only. However, we can
always override equals() method of Object class to
check the content.

17) Explain toString, equals and hashCode methods of


Object class
Ans:- public String toString()
returns the String representation of an instance.

public boolean equals(Object)


checks the equality of two references. If they
are referring to same instance then they are equal
otherwise not.
public int hashCode()
every object is given a unique number inside
memory. This number is called as hashcode. This
method returns the hashcode of caller object.

18) What do u mean by immutable class?


Ans:- when u perform any operation on any
instance, it will not affect the same one, rather it will
create a new one with modifications.

19) How to create immutable class in java?


Ans:- in order to create immutable class , we need to
follow some guidelines:
a) Don't provide "setter" methods — methods that
modify fields
b) If the instance fields include references to
mutable objects, don't allow those objects to be
changed:
i.e. don’t provide methods that modify the mutable
objects.
c) If the instance fields include references to mutable
objects, don't allow those objects to be changed:
Don't share references to the mutable objects.
d) If necessary, create copies to avoid returning the
originals in your methods
e) A class should be final

20) What are wrapper classes? What is their main


application?
Ans:- Wrapper classes are used to convert any
primitive type into an object. The primitive data
types are not objects, they do not belong to any
class, they are defined in the language itself. While
storing in data structures which support only
objects, it is required to convert the primitive type to
object first, so we go for wrapper class.
21) JDK 1.5 onwards, we can pass primitives (i.e.
int,char,float etc.) Directly to the method accepting
“java.lang.Object”. Does it mean that there is no use
of Wrapper classes now?
Ans:- No we can’t say that. It is true that JDK 1.5
onwards, we can pass primitives (i.e. int,char,float
etc.) Directly to the method accepting
“java.lang.Object”. But what actually happens
internally is, primitives are converted to Wrapper
(autoboxing) and then Wrapper being a subclass of
“java.lang.Object” can be passed to the method
accepting “java.lang.Object”. (widening)

22) Difference bet’n StringBuilder and StringBuffer


Ans:- StringBuilder is not thread-safe whereas
StringBuffer is thread-safe (all of its methods are
synchronized)

23) What is autoboxing and unboxing ?


Ans:- The automatic conversion of primitive
data types into its equivalent Wrapper
type is known as boxing and opposite
operation is known as unboxing.

24) Autoboxing and unboxing are limited to compiler


only . What do u mean by this ?
Ans:- all the autoboxing and unboxing instructions u
write in your source code are removed by compiler
while compiling the code. JVM does not understand
"autoboxing" and "unboxing".Hence compiler
removes them while compiling the source code.
25) What technique is used to make variable number of
arguments possible in java?
Ans:- compiler automatically convert variable
number of argument to array.

26) When u try to print any reference variable in java, u


get some meaningful output. What do u mean by
this?
Ans:- it means that the class must have overridden
“toString()” method.

27) Why can’t we instantiate abstract class?


Ans:- An Abstract class represents an abstract concept.
Take an example of vehicle class. You cannot build a
vehicle that is not something more specific.
An abstract class is not complete! The author marked it
abstract to tell you that some implementation is missing
in the code. The author has done some of the work, but
you must fill in some bits yourself to get it working. The
abstract keyword ensures that no one would
accidentally initiate this incomplete class.
28) Can abstract class have constructors in Java?
Ans:- Yes, abstract class can have constructor/s in
Java. Since you cannot create instance of abstract
class, constructor can only be called
during constructor chaining, i.e. when you create
instance of concrete implementation class. Now
question arises what is the purpose of constructor, if
you cannot instantiate abstract class? Well, it can
still be used to initialize instance members, which
are declared inside abstract class, and used by
various implementations. Also even if you don’t
provide any constructor, compiler will add default no
argument constructor in abstract class, without that
your subclass will not compile, since first statement
in any constructor implicitly calls super(), default
super class constructor in Java.

23) Can abstract class implement interface in Java?


Do they require to implement all methods?

ans:- Yes, abstract classes can implement interface


by using implements keyword. Since they are
abstract, they don’t need to implement all methods.
It’s good practice to provide an abstract base class,
along with an interface to declare Type. One
example of this is java.util.List interface and
corresponding java.util.AbstractList abstract class.
Since AbstractList implements all common
methods, concrete implementations
like LinkedList and ArrayList are free from burden of
implementing all methods, had they
implemented List interface directly. It’s best of both
world, you can get advantage of interface for
declaring type, and flexibility of abstract class to
implement common behavior at one place. 
24) Can abstract class be final in Java?
Ans:- No, abstract class cannot be final in Java.
Making them final will stop abstract class from being
extended, which is the only way to use abstract
class. They are also opposite of each
other, abstract keyword enforces to extend a class,
for using it, on the other hand, final
keyword prevents a class from being extended. In
real world also, abstract signifies incompleteness,
while final is used to demonstrate completeness.
Bottom line is, you cannot make your
class abstract and final in Java, at same time, it’s a
compile time error.

25) Can abstract class have static methods in Java?


Ans:- Yes, abstract class can have static methods.

26) Is it necessary for abstract class to have abstract


method?
ans:- No, It’s not mandatory for an abstract class to
have any abstract method. You can make a class
abstract in Java, by just using abstract keyword in
class declaration. Compiler will enforce all structural
restriction, applied to abstract class, e.g. not
allowing to create any instance. By the way, it’s
debatable whether you should have abstract
method inside abstract class or interface.
27) Can abstract class contain main method in Java?

ans:- Yes, abstract class can contain main method, it


just another static method and you can
execute Abstract class with main method, until you
don’t create any instance.

29) What do you mean by concrete class?


Ans:- a class which is not an abstract class i.e. a class
which is a complete class ,which can be instantiated
is known as “concrete class”.

30) What do you mean by “Functional Interface”?


Ans:- “Functional Interface” is the one having only
one abstract method also known as “SAM (Single
Abstract Method). It may have default or static
methods.

You might also like