SlideShare a Scribd company logo
Java	
  Interview	
  Questions	
  –	
  www.JavaInterview.in	
   1	
  
	
  
OOPS	
  
Following	
  picture	
  show	
  the	
  topics	
  we	
  would	
  cover	
  in	
  this	
  article.	
  
	
  
What	
  is	
  the	
  super	
  class	
  of	
  every	
  class	
  in	
  Java?	
  
Every class in java is a sub class of the class Object. When we create a class we inherit all the methods
and properties of Object class. Let’s look at a simple example:
	
  
String	
  str	
  =	
  "Testing";	
  
System.out.println(str.toString());	
  
System.out.println(str.hashCode());	
  
System.out.println(str.clone());	
  
	
  
if(str	
  instanceof	
  Object){	
  
	
  	
  	
  	
  System.out.println("I	
  extend	
  Object");//Will	
  be	
  printed	
  
}	
  
In the above example, toString, hashCode and clone methods for String class are inherited from Object
class and overridden.
Can	
  super	
  class	
  reference	
  variable	
  can	
  hold	
  an	
  object	
  of	
  sub	
  class?	
  
Yes. Look at the example below:
	
  
Actor reference variables actor1, actor2 hold the reference of objects of sub classes of Animal, Comedian
and Hero.
Since object is super class of all classes, an Object reference variable can also hold an instance of any
class.
2	
   Java	
  Interview	
  Questions	
  –	
  www.JavaInterview.in	
   	
  
	
  
//Object	
  is	
  super	
  class	
  of	
  all	
  java	
  classes	
  
Object	
  object	
  =	
  new	
  Hero();	
  	
  
	
  
public	
  class	
  Actor	
  {	
  
	
  	
  	
  	
  public	
  void	
  act(){	
  
	
  	
  	
  	
  	
  	
  	
  	
  System.out.println("Act");	
  
	
  	
  	
  	
  };	
  
}	
  
	
  
//IS-­‐A	
  relationship.	
  Hero	
  is-­‐a	
  Actor	
  
public	
  class	
  Hero	
  extends	
  Actor	
  {	
  
	
  	
  	
  	
  public	
  void	
  fight(){	
  
	
  	
  	
  	
  	
  	
  	
  	
  System.out.println("fight");	
  
	
  	
  	
  	
  };	
  
}	
  
	
  
//IS-­‐A	
  relationship.	
  Comedian	
  is-­‐a	
  Actor	
  
public	
  class	
  Comedian	
  extends	
  Actor	
  {	
  
	
  	
  	
  	
  public	
  void	
  performComedy(){	
  
	
  	
  	
  	
  	
  	
  	
  	
  System.out.println("Comedy");	
  
	
  	
  	
  	
  };	
  
}	
  
	
  
Actor	
  actor1	
  =	
  new	
  Comedian();	
  
Actor	
  actor2	
  =	
  new	
  Hero();	
  
Is	
  Multiple	
  Inheritance	
  allowed	
  in	
  Java?	
  
Multiple Inheritance results in a number of complexities. Java does not support Multiple Inheritance.
	
  
class	
  Dog	
  extends	
  Animal,	
  Pet	
  {	
  //COMPILER	
  ERROR	
  
}	
  
However, we can create an Inheritance Chain
class	
  Pet	
  extends	
  Animal	
  {	
  
}	
  
	
  
class	
  Dog	
  extends	
  Pet	
  {	
  
}	
  
What	
  is	
  Polymorphism?	
  
Refer	
  to	
  this	
  video(https://www.youtube.com/watch?v=t8PTatUXtpI)	
  for	
  a	
  clear	
  explanation	
  of	
  
polymorphism.	
  
Polymorphism	
  is	
  defined	
  as	
  “Same	
  Code”	
  giving	
  “Different	
  Behavior”.	
  Let’s	
  look	
  at	
  an	
  example.	
  	
  
Let’s	
  define	
  an	
  Animal	
  class	
  with	
  a	
  method	
  shout.	
  
public	
  class	
  Animal	
  {	
  
	
  	
  	
  	
  public	
  String	
  shout()	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  return	
  "Don't	
  Know!";	
  
	
  	
  	
  	
  }	
  
Java	
  Interview	
  Questions	
  –	
  www.JavaInterview.in	
   3	
  
	
  
}	
  
	
  
Let’s	
  create	
  two	
  new	
  sub	
  classes	
  of	
  Animal	
  overriding	
  the	
  existing	
  shout	
  method	
  in	
  Animal.	
  
class	
  Cat	
  extends	
  Animal	
  {	
  
	
  	
  	
  	
  public	
  String	
  shout()	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  return	
  "Meow	
  Meow";	
  
	
  	
  	
  	
  }	
  
}	
  
	
  
class	
  Dog	
  extends	
  Animal	
  {	
  
	
  	
  	
  	
  public	
  String	
  shout()	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  return	
  "BOW	
  BOW";	
  
	
  	
  	
  	
  }	
  
	
  
	
  	
  	
  	
  public	
  void	
  run(){	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  
	
  	
  	
  	
  }	
  
}	
  
	
  
Look	
  at	
  the	
  code	
  below.	
  An	
  instance	
  of	
  Animal	
  class	
  is	
  created.	
  shout	
  method	
  is	
  called.	
  	
  
Animal	
  animal1	
  =	
  new	
  Animal();	
  	
  	
  	
  	
  	
  	
  	
  	
  
System.out.println(	
  
	
  	
  	
  	
  	
  	
  	
  	
  animal1.shout());	
  //Don't	
  Know!	
  
	
  
Look	
  at	
  the	
  code	
  below.	
  An	
  instance	
  of	
  Dog	
  class	
  is	
  created	
  and	
  store	
  in	
  a	
  reference	
  variable	
  of	
  type	
  
Animal.	
  
Animal	
  animal2	
  =	
  new	
  Dog();	
  
	
  
//Reference	
  variable	
  type	
  =>	
  Animal	
  
//Object	
  referred	
  to	
  =>	
  Dog	
  
//Dog's	
  bark	
  method	
  is	
  called.	
  
System.out.println(	
  
	
  	
  	
  	
  	
  	
  	
  	
  animal2.shout());	
  //BOW	
  BOW	
  
	
  
When	
  shout	
  method	
  is	
  called	
  on	
  animal2,	
  it	
  invokes	
  the	
  shout	
  method	
  in	
  Dog	
  class	
  (type	
  of	
  the	
  object	
  
pointed	
  to	
  by	
  reference	
  variable	
  animal2).	
  
Even	
  though	
  dog	
  has	
  a	
  method	
  run,	
  it	
  cannot	
  be	
  invoked	
  using	
  super	
  class	
  reference	
  variable.	
  
//animal2.run();//COMPILE	
  ERROR	
  
What	
  is	
  the	
  use	
  of	
  instanceof	
  Operator	
  in	
  Java?	
  
instanceof operator checks if an object is of a particular type. Let us consider the following class and
interface declarations:
class	
  SuperClass	
  {	
  
};	
  
	
  
class	
  SubClass	
  extends	
  SuperClass	
  {	
  
};	
  
4	
   Java	
  Interview	
  Questions	
  –	
  www.JavaInterview.in	
   	
  
	
  
Java	
  Interview	
  Questions	
  –	
  www.JavaInterview.in	
  
At	
  http://www.JavaInterview.in,	
  we	
  want	
  you	
  to	
  clear	
  java	
  interview	
  with	
  ease.	
  So,	
  in	
  addition	
  to	
  
focussing	
  on	
  Core	
  and	
  Advanced	
  Java	
  we	
  also	
  focus	
  on	
  topics	
  like	
  Code	
  Reviews,	
  Performance,	
  	
  
Design	
  Patterns,	
  Spring	
  and	
  Struts.	
  
We	
  have	
  created	
  more	
  than	
  20	
  videos	
  to	
  help	
  you	
  understand	
  these	
  topics	
  and	
  become	
  an	
  expert	
  at	
  
them.	
  Visit	
  our	
  website	
  http://www.JavaInterview.in	
  for	
  complete	
  list	
  of	
  videos.	
  	
  Other	
  than	
  the	
  
videos,	
  we	
  answer	
  the	
  top	
  200	
  frequently	
  asked	
  interview	
  questions	
  on	
  our	
  website.	
  
With	
  more	
  900K	
  video	
  views	
  (Apr	
  2015),	
  we	
  are	
  the	
  most	
  popular	
  channel	
  on	
  Java	
  Interview	
  
Questions	
  on	
  YouTube.	
  
Register	
  here	
  for	
  more	
  updates	
  :	
  	
  
https://feedburner.google.com/fb/a/mailverify?uri=RithusTutorials	
  
POPULAR	
  VIDEOS	
  
Java	
  Interview	
  :	
  A	
  Freshers	
  Guide	
  -­‐	
  Part	
  1:	
  https://www.youtube.com/watch?v=njZ48YVkei0	
  
Java	
  Interview	
  :	
  A	
  Freshers	
  Guide	
  -­‐	
  Part	
  2:	
  https://www.youtube.com/watch?v=xyXuo0y-xoU	
  
Java	
  Interview	
  :	
  A	
  Guide	
  for	
  Experienced:	
  https://www.youtube.com/watch?v=0xcgzUdTO5M
Collections	
  Interview	
  Questions	
  1:	
  https://www.youtube.com/watch?v=GnR4hCvEIJQ
Collections	
  Interview	
  Questions	
  2:	
  https://www.youtube.com/watch?v=6dKGpOKAQqs
Collections	
  Interview	
  Questions	
  3:	
  https://www.youtube.com/watch?v=_JTIYhnLemA
Collections	
  Interview	
  Questions	
  4:	
  https://www.youtube.com/watch?v=ZNhT_Z8_q9s
Collections	
  Interview	
  Questions	
  5:	
  https://www.youtube.com/watch?v=W5c8uXi4qTw
	
  
interface	
  Interface	
  {	
  
};	
  
	
  
class	
  SuperClassImplementingInteface	
  implements	
  Interface	
  {	
  
};	
  
	
  
class	
  SubClass2	
  extends	
  SuperClassImplementingInteface	
  {	
  
};	
  
	
  
class	
  SomeOtherClass	
  {	
  
};	
  
	
  
Let’s	
  consider	
  the	
  code	
  below.	
  	
  We	
  create	
  a	
  few	
  instances	
  of	
  the	
  classes	
  declared	
  above.	
  
Java	
  Interview	
  Questions	
  –	
  www.JavaInterview.in	
   5	
  
	
  
SubClass	
  subClass	
  =	
  new	
  SubClass();	
  
Object	
  subClassObj	
  =	
  new	
  SubClass();	
  
	
  
SubClass2	
  subClass2	
  =	
  new	
  SubClass2();	
  
SomeOtherClass	
  someOtherClass	
  =	
  new	
  SomeOtherClass();	
  
	
  
Let’s	
  now	
  run	
  instanceof	
  operator	
  on	
  the	
  different	
  instances	
  created	
  earlier.	
  
System.out.println(subClass	
  instanceof	
  SubClass);//true	
  
System.out.println(subClass	
  instanceof	
  SuperClass);//true	
  
System.out.println(subClassObj	
  instanceof	
  SuperClass);//true	
  
	
  
System.out.println(subClass2	
  	
  
	
  	
  	
  	
  	
  	
  	
  	
  instanceof	
  SuperClassImplementingInteface);//true	
  
	
  
instanceof	
  can	
  be	
  used	
  with	
  interfaces	
  as	
  well.	
  Since	
  Super	
  Class	
  implements	
  the	
  interface,	
  below	
  code	
  
prints	
  true.	
  
System.out.println(subClass2	
  	
  
	
  	
  	
  	
  	
  	
  	
  	
  instanceof	
  Interface);//true	
  
	
  
If	
  the	
  type	
  compared	
  is	
  unrelated	
  to	
  the	
  object,	
  a	
  compilation	
  error	
  occurs.	
  
//System.out.println(subClass	
  	
  
//	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  instanceof	
  SomeOtherClass);//Compiler	
  Error	
  
	
  
Object	
  referred	
  by	
  subClassObj(SubClass)-­‐	
  NOT	
  of	
  type	
  SomeOtherClass	
  
System.out.println(subClassObj	
  instanceof	
  SomeOtherClass);//false	
  
What	
  is	
  an	
  Abstract	
  Class?	
  
An	
   abstract	
   class	
   (Video	
   Link	
   -­‐	
   https://www.youtube.com/watch?v=j3GLUcdlz1w )	
   is	
   a	
   class	
  
that	
  cannot	
  be	
  instantiated,	
  but	
  must	
  be	
  inherited	
  from.	
  An	
  abstract	
  class	
  may	
  be	
  fully	
  implemented,	
  
but	
  is	
  more	
  usually	
  partially	
  implemented	
  or	
  not	
  implemented	
  at	
  all,	
  thereby	
  encapsulating	
  common	
  
functionality	
  for	
  inherited	
  classes.
In	
   code	
   below	
   ”AbstractClassExample	
   ex	
   =	
   new	
   AbstractClassExample();”	
   gives	
   a	
   compilation	
   error	
  
because	
  AbstractClassExample	
  is	
  declared	
  with	
  keyword	
  abstract.	
  	
  
public	
  abstract	
  class	
  AbstractClassExample	
  {	
  
	
  	
  	
  	
  public	
  static	
  void	
  main(String[]	
  args)	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  //An	
  abstract	
  class	
  cannot	
  be	
  instantiated	
  
	
  	
  	
  	
  	
  	
  	
  	
  //Below	
  line	
  gives	
  compilation	
  error	
  if	
  uncommented	
  
	
  	
  	
  	
  	
  	
  	
  	
  //AbstractClassExample	
  ex	
  =	
  new	
  AbstractClassExample();	
  
	
  	
  	
  	
  }	
  
}	
  
How	
  do	
  you	
  define	
  an	
  abstract	
  method?	
  
An Abstract method does not contain body. An abstract method does not have any implementation. The
implementation of an abstract method should be provided in an over-riding method in a sub class.
	
  	
  	
  	
  //Abstract	
  Class	
  can	
  contain	
  0	
  or	
  more	
  abstract	
  methods	
  
	
  	
  	
  	
  //Abstract	
  method	
  does	
  not	
  have	
  a	
  body	
  
6	
   Java	
  Interview	
  Questions	
  –	
  www.JavaInterview.in	
   	
  
	
  
	
  	
  	
  	
  abstract	
  void	
  abstractMethod1();	
  
	
  	
  	
  	
  abstract	
  void	
  abstractMethod2();	
  
	
  
Abstract	
  method	
  can	
  be	
  declared	
  only	
  in	
  Abstract	
  Class.	
  In	
  the	
  example	
  below,	
  abstractMethod()	
  gives	
  a	
  
compiler	
  error	
  because	
  NormalClass	
  is	
  not	
  abstract.	
  
class	
  NormalClass{	
  
	
  	
  	
  	
  abstract	
  void	
  abstractMethod();//COMPILER	
  ERROR	
  
}	
  
What	
  is	
  Coupling?	
  
Coupling is a measure of how much a class is dependent on other classes. There should minimal
dependencies between classes. So, we should always aim for low coupling between classes.
Coupling	
  Example	
  Problem	
  
Consider	
  the	
  example	
  below:	
  
class	
  ShoppingCartEntry	
  {	
  
	
  	
  	
  	
  public	
  float	
  price;	
  
	
  	
  	
  	
  public	
  int	
  quantity;	
  
}	
  
	
  
class	
  ShoppingCart	
  {	
  
	
  	
  	
  	
  public	
  ShoppingCartEntry[]	
  items;	
  
}	
  
	
  
class	
  Order	
  {	
  
	
  	
  	
  	
  private	
  ShoppingCart	
  cart;	
  
	
  	
  	
  	
  private	
  float	
  salesTax;	
  
	
  
	
  	
  	
  	
  public	
  Order(ShoppingCart	
  cart,	
  float	
  salesTax)	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  this.cart	
  =	
  cart;	
  
	
  	
  	
  	
  	
  	
  	
  	
  this.salesTax	
  =	
  salesTax;	
  
	
  	
  	
  	
  }	
  
	
  
	
  	
  	
  	
  //	
  This	
  method	
  know	
  the	
  internal	
  details	
  of	
  ShoppingCartEntry	
  and	
  
	
  	
  	
  	
  //	
  ShoppingCart	
  classes.	
  If	
  there	
  is	
  any	
  change	
  in	
  any	
  of	
  those	
  
	
  	
  	
  	
  //	
  classes,	
  this	
  method	
  also	
  needs	
  to	
  change.	
  
	
  	
  	
  	
  public	
  float	
  orderTotalPrice()	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  float	
  cartTotalPrice	
  =	
  0;	
  
	
  	
  	
  	
  	
  	
  	
  	
  for	
  (int	
  i	
  =	
  0;	
  i	
  <	
  cart.items.length;	
  i++)	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  cartTotalPrice	
  +=	
  cart.items[i].price	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  *	
  cart.items[i].quantity;	
  
	
  	
  	
  	
  	
  	
  	
  	
  }	
  
	
  	
  	
  	
  	
  	
  	
  	
  cartTotalPrice	
  +=	
  cartTotalPrice	
  *	
  salesTax;	
  
	
  	
  	
  	
  	
  	
  	
  	
  return	
  cartTotalPrice;	
  
	
  	
  	
  	
  }	
  
}	
  
Method	
   orderTotalPrice	
   in	
   Order	
   class	
   is	
   coupled	
   heavily	
   with	
   ShoppingCartEntry	
   and	
  
ShoppingCart	
  classes.	
  	
  It	
  uses	
  different	
  properties	
  (items,	
  price,	
  quantity)	
  from	
  these	
  classes.	
  If	
  any	
  of	
  
these	
  properties	
  change,	
  orderTotalPrice	
  will	
  also	
  change.	
  This	
  is	
  not	
  good	
  for	
  Maintenance.	
  	
  
Java	
  Interview	
  Questions	
  –	
  www.JavaInterview.in	
   7	
  
	
  
Solution	
  
Consider a better implementation with lesser coupling between classes below: In this implementation,
changes in ShoppingCartEntry or CartContents might not affect Order class at all.
class	
  ShoppingCartEntry	
  
{	
  
	
  	
  	
  	
  float	
  price;	
  
	
  	
  	
  	
  int	
  quantity;	
  
	
  
	
  	
  	
  	
  public	
  float	
  getTotalPrice()	
  
	
  	
  	
  	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  return	
  price	
  *	
  quantity;	
  
	
  	
  	
  	
  }	
  
}	
  
	
  
class	
  CartContents	
  
{	
  
	
  	
  	
  	
  ShoppingCartEntry[]	
  items;	
  
	
  
	
  	
  	
  	
  public	
  float	
  getTotalPrice()	
  
	
  	
  	
  	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  float	
  totalPrice	
  =	
  0;	
  
	
  	
  	
  	
  	
  	
  	
  	
  for	
  (ShoppingCartEntry	
  item:items)	
  
	
  	
  	
  	
  	
  	
  	
  	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  totalPrice	
  +=	
  item.getTotalPrice();	
  
	
  	
  	
  	
  	
  	
  	
  	
  }	
  
	
  	
  	
  	
  	
  	
  	
  	
  return	
  totalPrice;	
  
	
  	
  	
  	
  }	
  
}	
  
	
  
class	
  Order	
  
{	
  
	
  	
  	
  	
  private	
  CartContents	
  cart;	
  
	
  	
  	
  	
  private	
  float	
  salesTax;	
  
	
  
	
  	
  	
  	
  public	
  Order(CartContents	
  cart,	
  float	
  salesTax)	
  
	
  	
  	
  	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  this.cart	
  =	
  cart;	
  
	
  	
  	
  	
  	
  	
  	
  	
  this.salesTax	
  =	
  salesTax;	
  
	
  	
  	
  	
  }	
  
	
  
	
  	
  	
  	
  public	
  float	
  totalPrice()	
  
	
  	
  	
  	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  return	
  cart.getTotalPrice()	
  *	
  (1.0f	
  +	
  salesTax);	
  
	
  	
  	
  	
  }	
  
}	
  
What	
  is	
  Cohesion?	
  
Cohesion	
   (Video	
   Link	
   -­‐	
   https://www.youtube.com/watch?v=BkcQWoF5124 )	
   is	
   a	
   measure	
   of	
  
how	
  related	
  the	
  responsibilities	
  of	
  a	
  class	
  are.	
  	
  A	
  class	
  must	
  be	
  highly	
  cohesive	
  i.e.	
  its	
  responsibilities	
  
(methods)	
  should	
  be	
  highly	
  related	
  to	
  one	
  another.	
  
8	
   Java	
  Interview	
  Questions	
  –	
  www.JavaInterview.in	
   	
  
	
  
Example	
  Problem	
  
Example	
   class	
   below	
   is	
   downloading	
   from	
   internet,	
   parsing	
   data	
   and	
   storing	
   data	
   to	
   database.	
   The	
  
responsibilities	
  of	
  this	
  class	
  are	
  not	
  really	
  related.	
  This	
  is	
  not	
  cohesive	
  class.	
  
class	
  DownloadAndStore{	
  
	
  	
  	
  	
  void	
  downloadFromInternet(){	
  
	
  	
  	
  	
  }	
  
	
  	
  	
  	
  	
  
	
  	
  	
  	
  void	
  parseData(){	
  
	
  	
  	
  	
  }	
  
	
  	
  	
  	
  	
  
	
  	
  	
  	
  void	
  storeIntoDatabase(){	
  
	
  	
  	
  	
  }	
  
	
  	
  	
  	
  	
  
	
  	
  	
  	
  void	
  doEverything(){	
  
	
  	
  	
  	
  	
  	
  	
  	
  downloadFromInternet();	
  
	
  	
  	
  	
  	
  	
  	
  	
  parseData();	
  
	
  	
  	
  	
  	
  	
  	
  	
  storeIntoDatabase();	
  
	
  	
  	
  	
  }	
  
}	
  
Solution
This is a better way of approaching the problem. Different classes have their own responsibilities.
class	
  InternetDownloader	
  {	
  
	
  	
  	
  	
  public	
  void	
  downloadFromInternet()	
  {	
  
	
  	
  	
  	
  }	
  
}	
  
	
  
class	
  DataParser	
  {	
  
	
  	
  	
  	
  public	
  void	
  parseData()	
  {	
  
	
  	
  	
  	
  }	
  
}	
  
	
  
class	
  DatabaseStorer	
  {	
  
	
  	
  	
  	
  public	
  void	
  storeIntoDatabase()	
  {	
  
	
  	
  	
  	
  }	
  
}	
  
	
  
class	
  DownloadAndStore	
  {	
  
	
  	
  	
  	
  void	
  doEverything()	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  new	
  InternetDownloader().downloadFromInternet();	
  
	
  	
  	
  	
  	
  	
  	
  	
  new	
  DataParser().parseData();	
  
	
  	
  	
  	
  	
  	
  	
  	
  new	
  DatabaseStorer().storeIntoDatabase();	
  
	
  	
  	
  	
  }	
  
}	
  
What	
  is	
  Encapsulation?	
  
Encapsulation is “hiding the implementation of a Class behind a well defined interface”. Encapsulation
helps us to change implementation of a class without breaking other code.
Java	
  Interview	
  Questions	
  –	
  www.JavaInterview.in	
   9	
  
	
  
Approach	
  1	
  
In	
  this	
  approach	
  we	
  create	
  a	
  public	
  variable	
  score.	
  The	
  main	
  method	
  directly	
  accesses	
  the	
  score	
  variable,	
  
updates	
  it.	
  
public	
  class	
  CricketScorer	
  {	
  
	
  	
  	
  	
  public	
  int	
  score;	
  
}	
  
	
  
Let’s	
  use	
  the	
  CricketScorer	
  class.	
  
public	
  static	
  void	
  main(String[]	
  args)	
  {	
  
CricketScorer	
  scorer	
  =	
  new	
  CricketScorer();	
  
scorer.score	
  =	
  scorer.score	
  +	
  4;	
  
}	
  
Approach	
  2	
  
In	
  this	
  approach,	
  we	
  make	
  score	
  as	
  private	
  and	
  access	
  value	
  through	
  get	
  and	
  set	
  methods.	
  However,	
  the	
  
logic	
  of	
  adding	
  4	
  to	
  the	
  score	
  is	
  performed	
  in	
  the	
  main	
  method.	
  
public	
  class	
  CricketScorer	
  {	
  
	
  	
  	
  	
  private	
  int	
  score;	
  
	
  
	
  	
  	
  	
  public	
  int	
  getScore()	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  return	
  score;	
  
	
  	
  	
  	
  }	
  
	
  
	
  	
  	
  	
  public	
  void	
  setScore(int	
  score)	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  this.score	
  =	
  score;	
  
	
  	
  	
  	
  }	
  
}	
  
	
  
Let’s	
  use	
  the	
  CricketScorer	
  class.	
  
	
  
public	
  static	
  void	
  main(String[]	
  args)	
  {	
  
CricketScorer	
  scorer	
  =	
  new	
  CricketScorer();	
  
	
  
int	
  score	
  =	
  scorer.getScore();	
  
scorer.setScore(score	
  +	
  4);	
  
}	
  
Approach	
  3	
  
In	
  this	
  approach	
  -­‐	
  For	
  better	
  encapsulation,	
  the	
  logic	
  of	
  doing	
  the	
  four	
  operation	
  also	
  is	
  moved	
  to	
  the	
  
CricketScorer	
  class.	
  
public	
  class	
  CricketScorer	
  {	
  
	
  	
  	
  	
  private	
  int	
  score;	
  
	
  	
  	
  	
  	
  
	
  	
  	
  	
  public	
  void	
  four()	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  score	
  +=	
  4;	
  
	
  	
  	
  	
  }	
  
	
  
}	
  
	
  
Let’s	
  use	
  the	
  CricketScorer	
  class.	
  
10	
   Java	
  Interview	
  Questions	
  –	
  www.JavaInterview.in	
   	
  
	
  
public	
  static	
  void	
  main(String[]	
  args)	
  {	
  
CricketScorer	
  scorer	
  =	
  new	
  CricketScorer();	
  
scorer.four();	
  
}	
  
Description	
  
In	
  terms	
  of	
  encapsulation	
  Approach	
  3	
  >	
  Approach	
  2	
  >	
  Approach	
  1.	
  In	
  Approach	
  3,	
  the	
  user	
  of	
  scorer	
  class	
  
does	
  not	
  even	
  know	
  that	
  there	
  is	
  a	
  variable	
  called	
  score.	
  Implementation	
  of	
  Scorer	
  can	
  change	
  without	
  
changing	
  other	
  classes	
  using	
  Scorer.	
  
What	
  is	
  Method	
  Overloading?	
  
A method having the same name as another method (in same class or a sub class) but having different
parameters is called an Overloaded Method.
Example	
  1	
  
doIt	
  method	
  is	
  overloaded	
  in	
  the	
  below	
  example:	
  
class	
  Foo{	
  
	
  	
  	
  	
  public	
  void	
  doIt(int	
  number){	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  
	
  	
  	
  	
  }	
  
	
  	
  	
  	
  public	
  void	
  doIt(String	
  string){	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  
	
  	
  	
  	
  }	
  
}	
  
Example	
  2	
  
Overloading	
  can	
  also	
  be	
  done	
  from	
  a	
  sub	
  class.	
  
class	
  Bar	
  extends	
  Foo{	
  
	
  	
  	
  	
  public	
  void	
  doIt(float	
  number){	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  
	
  	
  	
  	
  }	
  
}	
  
What	
  is	
  Method	
  Overriding?	
  
Creating a Sub Class Method with same signature as that of a method in SuperClass is called Method
Overriding.
Method	
  Overriding	
  Example	
  1:	
  
Let’s	
  define	
  an	
  Animal	
  class	
  with	
  a	
  method	
  shout.	
  
public	
  class	
  Animal	
  {	
  
	
  	
  	
  	
  public	
  String	
  bark()	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  return	
  "Don't	
  Know!";	
  
	
  	
  	
  	
  }	
  
}	
  
	
  
Let’s	
  create	
  a	
  sub	
  class	
  of	
  Animal	
  –	
  Cat	
  	
  -­‐	
  overriding	
  the	
  existing	
  shout	
  method	
  in	
  Animal.	
  
class	
  Cat	
  extends	
  Animal	
  {	
  
	
  	
  	
  	
  public	
  String	
  bark()	
  {	
  
Java	
  Interview	
  Questions	
  –	
  www.JavaInterview.in	
   1
1	
  	
  
	
  	
  	
  	
  	
  	
  	
  	
  return	
  "Meow	
  Meow";	
  
	
  	
  	
  	
  }	
  
}	
  
bark method in Cat class is overriding the bark method in Animal class.
What	
  is	
  an	
  Inner	
  Class?	
  
Inner	
  Classes	
  are	
  classes	
  which	
  are	
  declared	
  inside	
  other	
  classes.	
  Consider	
  the	
  following	
  example:	
  
class	
  OuterClass	
  {	
  
	
  
	
  	
  	
  	
  public	
  class	
  InnerClass	
  {	
  
	
  	
  	
  	
  }	
  
	
  
	
  	
  	
  	
  public	
  static	
  class	
  StaticNestedClass	
  {	
  
	
  	
  	
  	
  }	
  
	
  
}	
  
What	
  is	
  a	
  Static	
  Inner	
  Class?	
  
A	
  class	
  declared	
  directly	
  inside	
  another	
  class	
  and	
  declared	
  as	
  static.	
  In	
  the	
  example	
  above,	
  class	
  name	
  
StaticNestedClass	
  is	
  a	
  static	
  inner	
  class.	
  	
  
Can	
  you	
  create	
  an	
  inner	
  class	
  inside	
  a	
  method?	
  
Yes.	
   An	
   inner	
   class	
   can	
   be	
   declared	
   directly	
   inside	
   a	
   method.	
   In	
   the	
   example	
   below,	
   class	
   name	
  
MethodLocalInnerClass	
  is	
  a	
  method	
  inner	
  class.	
  	
  
class	
  OuterClass	
  {	
  
	
  
	
  	
  	
  	
  public	
  void	
  exampleMethod()	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  class	
  MethodLocalInnerClass	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  };	
  
	
  	
  	
  	
  }	
  
	
  
}	
  
Constructors	
  
Constructor (Youtube Video link - https://www.youtube.com/watch?v=XrdxGT2s9tc ) is
invoked whenever we create an instance(object) of a Class. We cannot create an object without a
constructor. If we do not provide a constructor, compiler provides a default no-argument constructor.
What	
  is	
  a	
  Default	
  Constructor?	
  
Default Constructor is the constructor that is provided by the compiler. It has no arguments. In the
example below, there are no Constructors defined in the Animal class. Compiler provides us with a
default constructor, which helps us create an instance of animal class.
	
  
public	
  class	
  Animal	
  {	
  
	
  	
  	
  	
  String	
  name;	
  
	
  
	
  	
  	
  	
  public	
  static	
  void	
  main(String[]	
  args)	
  {	
  
12	
   Java	
  Interview	
  Questions	
  –	
  www.JavaInterview.in	
   	
  
	
  
	
  	
  	
  	
  	
  	
  	
  	
  //	
  Compiler	
  provides	
  this	
  class	
  with	
  a	
  default	
  no-­‐argument	
  constructor.	
  
	
  	
  	
  	
  	
  	
  	
  	
  //	
  This	
  allows	
  us	
  to	
  create	
  an	
  instance	
  of	
  Animal	
  class.	
  
	
  	
  	
  	
  	
  	
  	
  	
  Animal	
  animal	
  =	
  new	
  Animal();	
  
	
  	
  	
  	
  }	
  
}	
  
How	
  do	
  you	
  call	
  a	
  Super	
  Class	
  Constructor	
  from	
  a	
  Constructor?
A constructor can call the constructor of a super class using the super() method call. Only constraint is
that it should be the first statement i
Both example constructors below can replaces the no argument "public Animal() " constructor in Example
3.
public	
  Animal()	
  {	
  
	
  	
  	
  	
  super();	
  
	
  	
  	
  	
  this.name	
  =	
  "Default	
  Name";	
  
}	
  
Can	
  a	
  constructor	
  be	
  called	
  directly	
  from	
  a	
  method?	
  	
  
A constructor cannot be explicitly called from any method except another constructor.
class	
  Animal	
  {	
  
	
  	
  	
  	
  String	
  name;	
  
	
  
	
  	
  	
  	
  public	
  Animal()	
  {	
  
	
  	
  	
  	
  }	
  
	
  
	
  	
  	
  	
  public	
  method()	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  Animal();//	
  Compiler	
  error	
  
	
  	
  	
  	
  }	
  
}	
  
Is	
  a	
  super	
  class	
  constructor	
  called	
  even	
  when	
  there	
  is	
  no	
  explicit	
  call	
  from	
  a	
  
sub	
  class	
  constructor?
If a super class constructor is not explicitly called from a sub class constructor, super class (no argument)
constructor is automatically invoked (as first line) from a sub class constructor.
Consider the example below:
class	
  Animal	
  {	
  
	
  	
  	
  	
  public	
  Animal()	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  System.out.println("Animal	
  Constructor");	
  
	
  	
  	
  	
  }	
  
}	
  
	
  
class	
  Dog	
  extends	
  Animal	
  {	
  
	
  	
  	
  	
  public	
  Dog()	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  System.out.println("Dog	
  Constructor");	
  
	
  	
  	
  	
  }	
  
}	
  
	
  
class	
  Labrador	
  extends	
  Dog	
  {	
  
	
  	
  	
  	
  public	
  Labrador()	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  System.out.println("Labrador	
  Constructor");	
  
	
  	
  	
  	
  }	
  
Java	
  Interview	
  Questions	
  –	
  www.JavaInterview.in	
   1
3	
  	
  
}	
  
	
  
public	
  class	
  ConstructorExamples	
  {	
  
	
  	
  	
  	
  public	
  static	
  void	
  main(String[]	
  args)	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  Labrador	
  labrador	
  =	
  new	
  Labrador();	
  
	
  	
  	
  	
  }	
  
}	
  
Program	
  Output	
  
Animal Constructor
Dog Constructor
Labrador Constructor
Interface	
  
What	
  is	
  an	
  Interface?	
  
An interface (YouTube video link - https://www.youtube.com/watch?v=VangB-sVNgg ) defines
a contract for responsibilities (methods) of a class.
How	
  do	
  you	
  define	
  an	
  Interface?	
  
An	
   interface	
   is	
   declared	
   by	
   using	
   the	
   keyword	
   interface.	
   Look	
   at	
   the	
   example	
   below:	
   Flyable	
   is	
   an	
  
interface.	
  
//public	
  abstract	
  are	
  not	
  necessary	
  
public	
  abstract	
  interface	
  Flyable	
  {	
  
	
  	
  	
  	
  //public	
  abstract	
  are	
  not	
  necessary	
  
	
  	
  	
  	
  public	
  abstract	
  void	
  fly();	
  
}	
  
How	
  do	
  you	
  implement	
  an	
  interface?
We can define a class implementing the interface by using the implements keyword. Let us look at a
couple of examples:
Example	
  1	
  
Class	
  Aeroplane	
  implements	
  Flyable	
  and	
  implements	
  the	
  abstract	
  method	
  fly().	
  
public	
  class	
  Aeroplane	
  implements	
  Flyable{	
  
	
  	
  	
  	
  @Override	
  
	
  	
  	
  	
  public	
  void	
  fly()	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  System.out.println("Aeroplane	
  is	
  flying");	
  
	
  	
  	
  	
  }	
  
}	
  
Example	
  2	
  
public	
  class	
  Bird	
  implements	
  Flyable{	
  
	
  	
  	
  	
  @Override	
  
	
  	
  	
  	
  public	
  void	
  fly()	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  System.out.println("Bird	
  is	
  flying");	
  
	
  	
  	
  	
  }	
  
}	
  
14	
   Java	
  Interview	
  Questions	
  –	
  www.JavaInterview.in	
   	
  
	
  
Can	
  you	
  tell	
  a	
  little	
  bit	
  more	
  about	
  interfaces?	
  
Variables	
   in	
   an	
   interface	
   are	
   always	
   public,	
   static,	
   final.	
   Variables	
   in	
   an	
   interface	
   cannot	
   be	
   declared	
  
private.	
  
interface	
  ExampleInterface1	
  {	
  
	
  	
  	
  	
  //By	
  default	
  -­‐	
  public	
  static	
  final.	
  No	
  other	
  modifier	
  allowed	
  
	
  	
  	
  	
  //value1,value2,value3,value4	
  all	
  are	
  -­‐	
  public	
  static	
  final	
  
	
  	
  	
  	
  int	
  value1	
  =	
  10;	
  
	
  	
  	
  	
  public	
  int	
  value2	
  =	
  15;	
  
	
  	
  	
  	
  public	
  static	
  int	
  value3	
  =	
  20;	
  
	
  	
  	
  	
  public	
  static	
  final	
  int	
  value4	
  =	
  25;	
  
	
  	
  	
  	
  //private	
  int	
  value5	
  =	
  10;//COMPILER	
  ERROR	
  
}	
  
Interface	
  methods	
  are	
  by	
  default	
  public	
  and	
  abstract.	
  A	
  concrete	
  method	
  (fully	
  defined	
  method)	
  cannot	
  
be	
  created	
  in	
  an	
  interface.	
  Consider	
  the	
  example	
  below:	
  
interface	
  ExampleInterface1	
  {	
  
	
  	
  	
  	
  //By	
  default	
  -­‐	
  public	
  abstract.	
  No	
  other	
  modifier	
  allowed	
  
	
  	
  	
  	
  void	
  method1();//method1	
  is	
  public	
  and	
  abstract	
  
	
  	
  	
  	
  //private	
  void	
  method6();//COMPILER	
  ERROR!	
  
	
  	
  	
  	
  	
  
	
  	
  	
  	
  /*//Interface	
  cannot	
  have	
  body	
  (definition)	
  of	
  a	
  method	
  
	
  	
  	
  	
  	
  	
  //This	
  method,	
  uncommented,	
  gives	
  COMPILER	
  ERROR!	
  
	
  	
  	
  	
  void	
  method5()	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  System.out.println("Method5");	
  
	
  	
  	
  	
  }	
  
	
  	
  	
  	
  	
  */	
  
}	
  
Can	
  you	
  extend	
  an	
  interface?	
  
An interface can extend another interface. Consider the example below:
	
  
interface	
  SubInterface1	
  extends	
  ExampleInterface1{	
  
	
  	
  	
  	
  void	
  method3();	
  
}	
  
Class	
   implementing	
   SubInterface1	
   should	
   implement	
   both	
   methods	
   -­‐	
   method3	
   and	
   method1(from	
  
ExampleInterface1)	
  
An interface cannot extend a class.
/*	
  //COMPILE	
  ERROR	
  IF	
  UnCommented	
  
	
  	
  	
  //Interface	
  cannot	
  extend	
  a	
  Class	
  
interface	
  SubInterface2	
  extends	
  Integer{	
  
	
  	
  	
  	
  void	
  method3();	
  
}	
  
*/	
  
Can	
  a	
  class	
  extend	
  multiple	
  interfaces?	
  
Java	
  Interview	
  Questions	
  –	
  www.JavaInterview.in	
   1
5	
  	
  
A class can implement multiple interfaces. It should implement all the method declared in all Interfaces
being implemented.
	
  
interface	
  ExampleInterface2	
  {	
  
	
  	
  	
  	
  void	
  method2();	
  
}	
  
	
  
class	
  SampleImpl	
  implements	
  ExampleInterface1,ExampleInterface2{	
  
	
  	
  	
  	
  /*	
  A	
  class	
  should	
  implement	
  all	
  the	
  methods	
  in	
  an	
  interface.	
  
	
  	
  	
  	
  	
  	
  	
  If	
  either	
  of	
  method1	
  or	
  method2	
  is	
  commented,	
  it	
  would	
  	
  
	
  	
  	
  	
  	
  	
  	
  result	
  in	
  compilation	
  error.	
  	
  
	
  	
  	
  	
  	
  */	
  
	
  	
  	
  	
  public	
  void	
  method2()	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  System.out.println("Sample	
  Implementation	
  for	
  Method2");	
  
	
  	
  	
  	
  }	
  
	
  
	
  	
  	
  	
  public	
  void	
  method1()	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  System.out.println("Sample	
  Implementation	
  for	
  Method1");	
  
	
  	
  	
  	
  }	
  
	
  	
  	
  	
  	
  
}	
  
	
  
POPULAR	
  VIDEOS	
  
Java	
  Interview	
  :	
  A	
  Freshers	
  Guide	
  -­‐	
  Part	
  1:	
  https://www.youtube.com/watch?v=njZ48YVkei0	
  
Java	
  Interview	
  :	
  A	
  Freshers	
  Guide	
  -­‐	
  Part	
  2:	
  https://www.youtube.com/watch?v=xyXuo0y-xoU	
  
Java	
  Interview	
  :	
  A	
  Guide	
  for	
  Experienced:	
  https://www.youtube.com/watch?v=0xcgzUdTO5M
Collections	
  Interview	
  Questions	
  1:	
  https://www.youtube.com/watch?v=GnR4hCvEIJQ
Collections	
  Interview	
  Questions	
  2:	
  https://www.youtube.com/watch?v=6dKGpOKAQqs
Collections	
  Interview	
  Questions	
  3:	
  https://www.youtube.com/watch?v=_JTIYhnLemA
Collections	
  Interview	
  Questions	
  4:	
  https://www.youtube.com/watch?v=ZNhT_Z8_q9s
Collections	
  Interview	
  Questions	
  5:	
  https://www.youtube.com/watch?v=W5c8uXi4qTw
	
  
Ad

More Related Content

What's hot (20)

Multi catch statement
Multi catch statementMulti catch statement
Multi catch statement
myrajendra
 
Java interview questions 2
Java interview questions 2Java interview questions 2
Java interview questions 2
Sherihan Anver
 
1z0-808-certification-questions-sample
1z0-808-certification-questions-sample1z0-808-certification-questions-sample
1z0-808-certification-questions-sample
java8certificationquestions
 
Concurrency on the JVM
Concurrency on the JVMConcurrency on the JVM
Concurrency on the JVM
Bernhard Huemer
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in Java
Vadym Lotar
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Monika Mishra
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
kamal kotecha
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handling
teach4uin
 
Java interview question
Java interview questionJava interview question
Java interview question
varatharajanrajeswar
 
Java/J2EE interview Qestions
Java/J2EE interview QestionsJava/J2EE interview Qestions
Java/J2EE interview Qestions
Arun Vasanth
 
B.Sc. III(VI Sem) Advance Java Unit1: Exception Handling & Multithreading
B.Sc. III(VI Sem) Advance Java Unit1: Exception Handling & MultithreadingB.Sc. III(VI Sem) Advance Java Unit1: Exception Handling & Multithreading
B.Sc. III(VI Sem) Advance Java Unit1: Exception Handling & Multithreading
Assistant Professor, Shri Shivaji Science College, Amravati
 
Questions of java
Questions of javaQuestions of java
Questions of java
Waseem Wasi
 
Java programming basics
Java programming basicsJava programming basics
Java programming basics
Hamid Ghorbani
 
Exceptions handling notes in JAVA
Exceptions handling notes in JAVAExceptions handling notes in JAVA
Exceptions handling notes in JAVA
Sunil Kumar Gunasekaran
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
Java2Blog
 
Lulu.com.java.j2 ee.job.interview.companion.2nd.edition.apr.2007
Lulu.com.java.j2 ee.job.interview.companion.2nd.edition.apr.2007Lulu.com.java.j2 ee.job.interview.companion.2nd.edition.apr.2007
Lulu.com.java.j2 ee.job.interview.companion.2nd.edition.apr.2007
Arun Kumar
 
Java review: try catch
Java review: try catchJava review: try catch
Java review: try catch
Muzahidul Islam
 
Easymock Tutorial
Easymock TutorialEasymock Tutorial
Easymock Tutorial
Sbin m
 
Exception handling
Exception handlingException handling
Exception handling
Minal Maniar
 
Java Interview Questions by NageswaraRao
Java Interview Questions by NageswaraRaoJava Interview Questions by NageswaraRao
Java Interview Questions by NageswaraRao
JavabynataraJ
 
Multi catch statement
Multi catch statementMulti catch statement
Multi catch statement
myrajendra
 
Java interview questions 2
Java interview questions 2Java interview questions 2
Java interview questions 2
Sherihan Anver
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in Java
Vadym Lotar
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Monika Mishra
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
kamal kotecha
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handling
teach4uin
 
Java/J2EE interview Qestions
Java/J2EE interview QestionsJava/J2EE interview Qestions
Java/J2EE interview Qestions
Arun Vasanth
 
Questions of java
Questions of javaQuestions of java
Questions of java
Waseem Wasi
 
Java programming basics
Java programming basicsJava programming basics
Java programming basics
Hamid Ghorbani
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
Java2Blog
 
Lulu.com.java.j2 ee.job.interview.companion.2nd.edition.apr.2007
Lulu.com.java.j2 ee.job.interview.companion.2nd.edition.apr.2007Lulu.com.java.j2 ee.job.interview.companion.2nd.edition.apr.2007
Lulu.com.java.j2 ee.job.interview.companion.2nd.edition.apr.2007
Arun Kumar
 
Easymock Tutorial
Easymock TutorialEasymock Tutorial
Easymock Tutorial
Sbin m
 
Exception handling
Exception handlingException handling
Exception handling
Minal Maniar
 
Java Interview Questions by NageswaraRao
Java Interview Questions by NageswaraRaoJava Interview Questions by NageswaraRao
Java Interview Questions by NageswaraRao
JavabynataraJ
 

Viewers also liked (19)

Core java interview questions
Core java interview questionsCore java interview questions
Core java interview questions
rithustutorials
 
Jira work flows
Jira work flowsJira work flows
Jira work flows
Shivaraj R
 
Core java interview questions
Core java interview questionsCore java interview questions
Core java interview questions
Vinay Kumar
 
Java interview questions
Java interview questionsJava interview questions
Java interview questions
rithustutorials
 
Java interview questions
Java interview questionsJava interview questions
Java interview questions
G C Reddy Technologies
 
C++ interview question
C++ interview questionC++ interview question
C++ interview question
Durgesh Tripathi
 
Preview java j2_ee_book
Preview java j2_ee_bookPreview java j2_ee_book
Preview java j2_ee_book
Subhadip Pal
 
Cucumber questions
Cucumber questionsCucumber questions
Cucumber questions
Shivaraj R
 
Data structure-question-bank
Data structure-question-bankData structure-question-bank
Data structure-question-bank
Jagan Mohan Bishoyi
 
Advanced data structures slide 1 2
Advanced data structures slide 1 2Advanced data structures slide 1 2
Advanced data structures slide 1 2
jomerson remorosa
 
Html, xml and java script
Html, xml and java scriptHtml, xml and java script
Html, xml and java script
Rajeev Uppala
 
Dbms Interview Question And Answer
Dbms Interview Question And AnswerDbms Interview Question And Answer
Dbms Interview Question And Answer
Jagan Mohan Bishoyi
 
Networking Basics
Networking BasicsNetworking Basics
Networking Basics
Jagan Mohan Bishoyi
 
C interview Question and Answer
C interview Question and AnswerC interview Question and Answer
C interview Question and Answer
Jagan Mohan Bishoyi
 
Java data structures for principled programmer
Java data structures for principled programmerJava data structures for principled programmer
Java data structures for principled programmer
spnr15z
 
Workday hcm interview questions
Workday hcm interview questionsWorkday hcm interview questions
Workday hcm interview questions
enrollmy training
 
Oracle Fusion v/s Workday
Oracle Fusion v/s WorkdayOracle Fusion v/s Workday
Oracle Fusion v/s Workday
Mayda Barsumyan
 
C++ Interview Question And Answer
C++ Interview Question And AnswerC++ Interview Question And Answer
C++ Interview Question And Answer
Jagan Mohan Bishoyi
 
Most Asked Java Interview Question and Answer
Most Asked Java Interview Question and AnswerMost Asked Java Interview Question and Answer
Most Asked Java Interview Question and Answer
TOPS Technologies
 
Core java interview questions
Core java interview questionsCore java interview questions
Core java interview questions
rithustutorials
 
Jira work flows
Jira work flowsJira work flows
Jira work flows
Shivaraj R
 
Core java interview questions
Core java interview questionsCore java interview questions
Core java interview questions
Vinay Kumar
 
Java interview questions
Java interview questionsJava interview questions
Java interview questions
rithustutorials
 
Preview java j2_ee_book
Preview java j2_ee_bookPreview java j2_ee_book
Preview java j2_ee_book
Subhadip Pal
 
Cucumber questions
Cucumber questionsCucumber questions
Cucumber questions
Shivaraj R
 
Advanced data structures slide 1 2
Advanced data structures slide 1 2Advanced data structures slide 1 2
Advanced data structures slide 1 2
jomerson remorosa
 
Html, xml and java script
Html, xml and java scriptHtml, xml and java script
Html, xml and java script
Rajeev Uppala
 
Dbms Interview Question And Answer
Dbms Interview Question And AnswerDbms Interview Question And Answer
Dbms Interview Question And Answer
Jagan Mohan Bishoyi
 
Java data structures for principled programmer
Java data structures for principled programmerJava data structures for principled programmer
Java data structures for principled programmer
spnr15z
 
Workday hcm interview questions
Workday hcm interview questionsWorkday hcm interview questions
Workday hcm interview questions
enrollmy training
 
Oracle Fusion v/s Workday
Oracle Fusion v/s WorkdayOracle Fusion v/s Workday
Oracle Fusion v/s Workday
Mayda Barsumyan
 
C++ Interview Question And Answer
C++ Interview Question And AnswerC++ Interview Question And Answer
C++ Interview Question And Answer
Jagan Mohan Bishoyi
 
Most Asked Java Interview Question and Answer
Most Asked Java Interview Question and AnswerMost Asked Java Interview Question and Answer
Most Asked Java Interview Question and Answer
TOPS Technologies
 
Ad

Similar to Java object oriented programming - OOPS (20)

Introduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptxIntroduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptx
Poonam60376
 
Comprehensive JavaScript Cheat Sheet for Quick Reference and Mastery
Comprehensive JavaScript Cheat Sheet for Quick Reference and MasteryComprehensive JavaScript Cheat Sheet for Quick Reference and Mastery
Comprehensive JavaScript Cheat Sheet for Quick Reference and Mastery
pavanbackup22
 
JavaScript Cheatsheets with easy way .pdf
JavaScript Cheatsheets with easy way .pdfJavaScript Cheatsheets with easy way .pdf
JavaScript Cheatsheets with easy way .pdf
ranjanadeore1
 
Basics to java programming and concepts of java
Basics to java programming and concepts of javaBasics to java programming and concepts of java
Basics to java programming and concepts of java
1747503gunavardhanre
 
Lect 1-java object-classes
Lect 1-java object-classesLect 1-java object-classes
Lect 1-java object-classes
Fajar Baskoro
 
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptxSodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
RudranilDas11
 
Learn java objects inheritance-overriding-polymorphism
Learn java objects  inheritance-overriding-polymorphismLearn java objects  inheritance-overriding-polymorphism
Learn java objects inheritance-overriding-polymorphism
TOPS Technologies
 
Top 50 Java Interviews Questions | Tutort Academy - Course for Working Profes...
Top 50 Java Interviews Questions | Tutort Academy - Course for Working Profes...Top 50 Java Interviews Questions | Tutort Academy - Course for Working Profes...
Top 50 Java Interviews Questions | Tutort Academy - Course for Working Profes...
Tutort Academy
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
Tech_MX
 
Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#
Abid Kohistani
 
coding assignment help : Java question
coding assignment help : Java questioncoding assignment help : Java question
coding assignment help : Java question
Coding Assignment Help
 
java_inheritance.pdf
java_inheritance.pdfjava_inheritance.pdf
java_inheritance.pdf
JayMistry91473
 
Java Interview Questions PDF By ScholarHat
Java Interview Questions PDF By ScholarHatJava Interview Questions PDF By ScholarHat
Java Interview Questions PDF By ScholarHat
Scholarhat
 
Modules 333333333³3444444444444444444.pptx
Modules 333333333³3444444444444444444.pptxModules 333333333³3444444444444444444.pptx
Modules 333333333³3444444444444444444.pptx
radhikacordise
 
Java For Automation
Java   For AutomationJava   For Automation
Java For Automation
Abhijeet Dubey
 
Java session4
Java session4Java session4
Java session4
Jigarthacker
 
1669617800196.pdf
1669617800196.pdf1669617800196.pdf
1669617800196.pdf
venud11
 
Chapter5.pptxfghwryhYETHYETH67IOIKUTJJUILOUI
Chapter5.pptxfghwryhYETHYETH67IOIKUTJJUILOUIChapter5.pptxfghwryhYETHYETH67IOIKUTJJUILOUI
Chapter5.pptxfghwryhYETHYETH67IOIKUTJJUILOUI
berihun18
 
Week 8,9,10 of lab of data communication .pdf
Week 8,9,10 of lab of data communication .pdfWeek 8,9,10 of lab of data communication .pdf
Week 8,9,10 of lab of data communication .pdf
nimrastorage123
 
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdfch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
bca23189c
 
Introduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptxIntroduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptx
Poonam60376
 
Comprehensive JavaScript Cheat Sheet for Quick Reference and Mastery
Comprehensive JavaScript Cheat Sheet for Quick Reference and MasteryComprehensive JavaScript Cheat Sheet for Quick Reference and Mastery
Comprehensive JavaScript Cheat Sheet for Quick Reference and Mastery
pavanbackup22
 
JavaScript Cheatsheets with easy way .pdf
JavaScript Cheatsheets with easy way .pdfJavaScript Cheatsheets with easy way .pdf
JavaScript Cheatsheets with easy way .pdf
ranjanadeore1
 
Basics to java programming and concepts of java
Basics to java programming and concepts of javaBasics to java programming and concepts of java
Basics to java programming and concepts of java
1747503gunavardhanre
 
Lect 1-java object-classes
Lect 1-java object-classesLect 1-java object-classes
Lect 1-java object-classes
Fajar Baskoro
 
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptxSodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
RudranilDas11
 
Learn java objects inheritance-overriding-polymorphism
Learn java objects  inheritance-overriding-polymorphismLearn java objects  inheritance-overriding-polymorphism
Learn java objects inheritance-overriding-polymorphism
TOPS Technologies
 
Top 50 Java Interviews Questions | Tutort Academy - Course for Working Profes...
Top 50 Java Interviews Questions | Tutort Academy - Course for Working Profes...Top 50 Java Interviews Questions | Tutort Academy - Course for Working Profes...
Top 50 Java Interviews Questions | Tutort Academy - Course for Working Profes...
Tutort Academy
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
Tech_MX
 
Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#
Abid Kohistani
 
coding assignment help : Java question
coding assignment help : Java questioncoding assignment help : Java question
coding assignment help : Java question
Coding Assignment Help
 
Java Interview Questions PDF By ScholarHat
Java Interview Questions PDF By ScholarHatJava Interview Questions PDF By ScholarHat
Java Interview Questions PDF By ScholarHat
Scholarhat
 
Modules 333333333³3444444444444444444.pptx
Modules 333333333³3444444444444444444.pptxModules 333333333³3444444444444444444.pptx
Modules 333333333³3444444444444444444.pptx
radhikacordise
 
1669617800196.pdf
1669617800196.pdf1669617800196.pdf
1669617800196.pdf
venud11
 
Chapter5.pptxfghwryhYETHYETH67IOIKUTJJUILOUI
Chapter5.pptxfghwryhYETHYETH67IOIKUTJJUILOUIChapter5.pptxfghwryhYETHYETH67IOIKUTJJUILOUI
Chapter5.pptxfghwryhYETHYETH67IOIKUTJJUILOUI
berihun18
 
Week 8,9,10 of lab of data communication .pdf
Week 8,9,10 of lab of data communication .pdfWeek 8,9,10 of lab of data communication .pdf
Week 8,9,10 of lab of data communication .pdf
nimrastorage123
 
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdfch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
bca23189c
 
Ad

Recently uploaded (20)

Presentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem KayaPresentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem Kaya
MIPLM
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
Exercise Physiology MCQS By DR. NASIR MUSTAFA
Exercise Physiology MCQS By DR. NASIR MUSTAFAExercise Physiology MCQS By DR. NASIR MUSTAFA
Exercise Physiology MCQS By DR. NASIR MUSTAFA
Dr. Nasir Mustafa
 
APM Midlands Region April 2025 Sacha Hind Circulated.pdf
APM Midlands Region April 2025 Sacha Hind Circulated.pdfAPM Midlands Region April 2025 Sacha Hind Circulated.pdf
APM Midlands Region April 2025 Sacha Hind Circulated.pdf
Association for Project Management
 
"Basics of Heterocyclic Compounds and Their Naming Rules"
"Basics of Heterocyclic Compounds and Their Naming Rules""Basics of Heterocyclic Compounds and Their Naming Rules"
"Basics of Heterocyclic Compounds and Their Naming Rules"
rupalinirmalbpharm
 
Operations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdfOperations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdf
Arab Academy for Science, Technology and Maritime Transport
 
Contact Lens:::: An Overview.pptx.: Optometry
Contact Lens:::: An Overview.pptx.: OptometryContact Lens:::: An Overview.pptx.: Optometry
Contact Lens:::: An Overview.pptx.: Optometry
MushahidRaza8
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
Engage Donors Through Powerful Storytelling.pdf
Engage Donors Through Powerful Storytelling.pdfEngage Donors Through Powerful Storytelling.pdf
Engage Donors Through Powerful Storytelling.pdf
TechSoup
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdfBiophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
PKLI-Institute of Nursing and Allied Health Sciences Lahore , Pakistan.
 
03#UNTAGGED. Generosity in architecture.
03#UNTAGGED. Generosity in architecture.03#UNTAGGED. Generosity in architecture.
03#UNTAGGED. Generosity in architecture.
MCH
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
Kenan Fellows Participants, Projects 2025-26 Cohort
Kenan Fellows Participants, Projects 2025-26 CohortKenan Fellows Participants, Projects 2025-26 Cohort
Kenan Fellows Participants, Projects 2025-26 Cohort
EducationNC
 
Presentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem KayaPresentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem Kaya
MIPLM
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
Exercise Physiology MCQS By DR. NASIR MUSTAFA
Exercise Physiology MCQS By DR. NASIR MUSTAFAExercise Physiology MCQS By DR. NASIR MUSTAFA
Exercise Physiology MCQS By DR. NASIR MUSTAFA
Dr. Nasir Mustafa
 
"Basics of Heterocyclic Compounds and Their Naming Rules"
"Basics of Heterocyclic Compounds and Their Naming Rules""Basics of Heterocyclic Compounds and Their Naming Rules"
"Basics of Heterocyclic Compounds and Their Naming Rules"
rupalinirmalbpharm
 
Contact Lens:::: An Overview.pptx.: Optometry
Contact Lens:::: An Overview.pptx.: OptometryContact Lens:::: An Overview.pptx.: Optometry
Contact Lens:::: An Overview.pptx.: Optometry
MushahidRaza8
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
Engage Donors Through Powerful Storytelling.pdf
Engage Donors Through Powerful Storytelling.pdfEngage Donors Through Powerful Storytelling.pdf
Engage Donors Through Powerful Storytelling.pdf
TechSoup
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
03#UNTAGGED. Generosity in architecture.
03#UNTAGGED. Generosity in architecture.03#UNTAGGED. Generosity in architecture.
03#UNTAGGED. Generosity in architecture.
MCH
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
Kenan Fellows Participants, Projects 2025-26 Cohort
Kenan Fellows Participants, Projects 2025-26 CohortKenan Fellows Participants, Projects 2025-26 Cohort
Kenan Fellows Participants, Projects 2025-26 Cohort
EducationNC
 

Java object oriented programming - OOPS

  • 1. Java  Interview  Questions  –  www.JavaInterview.in   1     OOPS   Following  picture  show  the  topics  we  would  cover  in  this  article.     What  is  the  super  class  of  every  class  in  Java?   Every class in java is a sub class of the class Object. When we create a class we inherit all the methods and properties of Object class. Let’s look at a simple example:   String  str  =  "Testing";   System.out.println(str.toString());   System.out.println(str.hashCode());   System.out.println(str.clone());     if(str  instanceof  Object){          System.out.println("I  extend  Object");//Will  be  printed   }   In the above example, toString, hashCode and clone methods for String class are inherited from Object class and overridden. Can  super  class  reference  variable  can  hold  an  object  of  sub  class?   Yes. Look at the example below:   Actor reference variables actor1, actor2 hold the reference of objects of sub classes of Animal, Comedian and Hero. Since object is super class of all classes, an Object reference variable can also hold an instance of any class.
  • 2. 2   Java  Interview  Questions  –  www.JavaInterview.in       //Object  is  super  class  of  all  java  classes   Object  object  =  new  Hero();       public  class  Actor  {          public  void  act(){                  System.out.println("Act");          };   }     //IS-­‐A  relationship.  Hero  is-­‐a  Actor   public  class  Hero  extends  Actor  {          public  void  fight(){                  System.out.println("fight");          };   }     //IS-­‐A  relationship.  Comedian  is-­‐a  Actor   public  class  Comedian  extends  Actor  {          public  void  performComedy(){                  System.out.println("Comedy");          };   }     Actor  actor1  =  new  Comedian();   Actor  actor2  =  new  Hero();   Is  Multiple  Inheritance  allowed  in  Java?   Multiple Inheritance results in a number of complexities. Java does not support Multiple Inheritance.   class  Dog  extends  Animal,  Pet  {  //COMPILER  ERROR   }   However, we can create an Inheritance Chain class  Pet  extends  Animal  {   }     class  Dog  extends  Pet  {   }   What  is  Polymorphism?   Refer  to  this  video(https://www.youtube.com/watch?v=t8PTatUXtpI)  for  a  clear  explanation  of   polymorphism.   Polymorphism  is  defined  as  “Same  Code”  giving  “Different  Behavior”.  Let’s  look  at  an  example.     Let’s  define  an  Animal  class  with  a  method  shout.   public  class  Animal  {          public  String  shout()  {                  return  "Don't  Know!";          }  
  • 3. Java  Interview  Questions  –  www.JavaInterview.in   3     }     Let’s  create  two  new  sub  classes  of  Animal  overriding  the  existing  shout  method  in  Animal.   class  Cat  extends  Animal  {          public  String  shout()  {                  return  "Meow  Meow";          }   }     class  Dog  extends  Animal  {          public  String  shout()  {                  return  "BOW  BOW";          }            public  void  run(){                            }   }     Look  at  the  code  below.  An  instance  of  Animal  class  is  created.  shout  method  is  called.     Animal  animal1  =  new  Animal();                   System.out.println(                  animal1.shout());  //Don't  Know!     Look  at  the  code  below.  An  instance  of  Dog  class  is  created  and  store  in  a  reference  variable  of  type   Animal.   Animal  animal2  =  new  Dog();     //Reference  variable  type  =>  Animal   //Object  referred  to  =>  Dog   //Dog's  bark  method  is  called.   System.out.println(                  animal2.shout());  //BOW  BOW     When  shout  method  is  called  on  animal2,  it  invokes  the  shout  method  in  Dog  class  (type  of  the  object   pointed  to  by  reference  variable  animal2).   Even  though  dog  has  a  method  run,  it  cannot  be  invoked  using  super  class  reference  variable.   //animal2.run();//COMPILE  ERROR   What  is  the  use  of  instanceof  Operator  in  Java?   instanceof operator checks if an object is of a particular type. Let us consider the following class and interface declarations: class  SuperClass  {   };     class  SubClass  extends  SuperClass  {   };  
  • 4. 4   Java  Interview  Questions  –  www.JavaInterview.in       Java  Interview  Questions  –  www.JavaInterview.in   At  http://www.JavaInterview.in,  we  want  you  to  clear  java  interview  with  ease.  So,  in  addition  to   focussing  on  Core  and  Advanced  Java  we  also  focus  on  topics  like  Code  Reviews,  Performance,     Design  Patterns,  Spring  and  Struts.   We  have  created  more  than  20  videos  to  help  you  understand  these  topics  and  become  an  expert  at   them.  Visit  our  website  http://www.JavaInterview.in  for  complete  list  of  videos.    Other  than  the   videos,  we  answer  the  top  200  frequently  asked  interview  questions  on  our  website.   With  more  900K  video  views  (Apr  2015),  we  are  the  most  popular  channel  on  Java  Interview   Questions  on  YouTube.   Register  here  for  more  updates  :     https://feedburner.google.com/fb/a/mailverify?uri=RithusTutorials   POPULAR  VIDEOS   Java  Interview  :  A  Freshers  Guide  -­‐  Part  1:  https://www.youtube.com/watch?v=njZ48YVkei0   Java  Interview  :  A  Freshers  Guide  -­‐  Part  2:  https://www.youtube.com/watch?v=xyXuo0y-xoU   Java  Interview  :  A  Guide  for  Experienced:  https://www.youtube.com/watch?v=0xcgzUdTO5M Collections  Interview  Questions  1:  https://www.youtube.com/watch?v=GnR4hCvEIJQ Collections  Interview  Questions  2:  https://www.youtube.com/watch?v=6dKGpOKAQqs Collections  Interview  Questions  3:  https://www.youtube.com/watch?v=_JTIYhnLemA Collections  Interview  Questions  4:  https://www.youtube.com/watch?v=ZNhT_Z8_q9s Collections  Interview  Questions  5:  https://www.youtube.com/watch?v=W5c8uXi4qTw   interface  Interface  {   };     class  SuperClassImplementingInteface  implements  Interface  {   };     class  SubClass2  extends  SuperClassImplementingInteface  {   };     class  SomeOtherClass  {   };     Let’s  consider  the  code  below.    We  create  a  few  instances  of  the  classes  declared  above.  
  • 5. Java  Interview  Questions  –  www.JavaInterview.in   5     SubClass  subClass  =  new  SubClass();   Object  subClassObj  =  new  SubClass();     SubClass2  subClass2  =  new  SubClass2();   SomeOtherClass  someOtherClass  =  new  SomeOtherClass();     Let’s  now  run  instanceof  operator  on  the  different  instances  created  earlier.   System.out.println(subClass  instanceof  SubClass);//true   System.out.println(subClass  instanceof  SuperClass);//true   System.out.println(subClassObj  instanceof  SuperClass);//true     System.out.println(subClass2                    instanceof  SuperClassImplementingInteface);//true     instanceof  can  be  used  with  interfaces  as  well.  Since  Super  Class  implements  the  interface,  below  code   prints  true.   System.out.println(subClass2                    instanceof  Interface);//true     If  the  type  compared  is  unrelated  to  the  object,  a  compilation  error  occurs.   //System.out.println(subClass     //                        instanceof  SomeOtherClass);//Compiler  Error     Object  referred  by  subClassObj(SubClass)-­‐  NOT  of  type  SomeOtherClass   System.out.println(subClassObj  instanceof  SomeOtherClass);//false   What  is  an  Abstract  Class?   An   abstract   class   (Video   Link   -­‐   https://www.youtube.com/watch?v=j3GLUcdlz1w )   is   a   class   that  cannot  be  instantiated,  but  must  be  inherited  from.  An  abstract  class  may  be  fully  implemented,   but  is  more  usually  partially  implemented  or  not  implemented  at  all,  thereby  encapsulating  common   functionality  for  inherited  classes. In   code   below   ”AbstractClassExample   ex   =   new   AbstractClassExample();”   gives   a   compilation   error   because  AbstractClassExample  is  declared  with  keyword  abstract.     public  abstract  class  AbstractClassExample  {          public  static  void  main(String[]  args)  {                  //An  abstract  class  cannot  be  instantiated                  //Below  line  gives  compilation  error  if  uncommented                  //AbstractClassExample  ex  =  new  AbstractClassExample();          }   }   How  do  you  define  an  abstract  method?   An Abstract method does not contain body. An abstract method does not have any implementation. The implementation of an abstract method should be provided in an over-riding method in a sub class.        //Abstract  Class  can  contain  0  or  more  abstract  methods          //Abstract  method  does  not  have  a  body  
  • 6. 6   Java  Interview  Questions  –  www.JavaInterview.in              abstract  void  abstractMethod1();          abstract  void  abstractMethod2();     Abstract  method  can  be  declared  only  in  Abstract  Class.  In  the  example  below,  abstractMethod()  gives  a   compiler  error  because  NormalClass  is  not  abstract.   class  NormalClass{          abstract  void  abstractMethod();//COMPILER  ERROR   }   What  is  Coupling?   Coupling is a measure of how much a class is dependent on other classes. There should minimal dependencies between classes. So, we should always aim for low coupling between classes. Coupling  Example  Problem   Consider  the  example  below:   class  ShoppingCartEntry  {          public  float  price;          public  int  quantity;   }     class  ShoppingCart  {          public  ShoppingCartEntry[]  items;   }     class  Order  {          private  ShoppingCart  cart;          private  float  salesTax;            public  Order(ShoppingCart  cart,  float  salesTax)  {                  this.cart  =  cart;                  this.salesTax  =  salesTax;          }            //  This  method  know  the  internal  details  of  ShoppingCartEntry  and          //  ShoppingCart  classes.  If  there  is  any  change  in  any  of  those          //  classes,  this  method  also  needs  to  change.          public  float  orderTotalPrice()  {                  float  cartTotalPrice  =  0;                  for  (int  i  =  0;  i  <  cart.items.length;  i++)  {                          cartTotalPrice  +=  cart.items[i].price                                          *  cart.items[i].quantity;                  }                  cartTotalPrice  +=  cartTotalPrice  *  salesTax;                  return  cartTotalPrice;          }   }   Method   orderTotalPrice   in   Order   class   is   coupled   heavily   with   ShoppingCartEntry   and   ShoppingCart  classes.    It  uses  different  properties  (items,  price,  quantity)  from  these  classes.  If  any  of   these  properties  change,  orderTotalPrice  will  also  change.  This  is  not  good  for  Maintenance.    
  • 7. Java  Interview  Questions  –  www.JavaInterview.in   7     Solution   Consider a better implementation with lesser coupling between classes below: In this implementation, changes in ShoppingCartEntry or CartContents might not affect Order class at all. class  ShoppingCartEntry   {          float  price;          int  quantity;            public  float  getTotalPrice()          {                  return  price  *  quantity;          }   }     class  CartContents   {          ShoppingCartEntry[]  items;            public  float  getTotalPrice()          {                  float  totalPrice  =  0;                  for  (ShoppingCartEntry  item:items)                  {                          totalPrice  +=  item.getTotalPrice();                  }                  return  totalPrice;          }   }     class  Order   {          private  CartContents  cart;          private  float  salesTax;            public  Order(CartContents  cart,  float  salesTax)          {                  this.cart  =  cart;                  this.salesTax  =  salesTax;          }            public  float  totalPrice()          {                  return  cart.getTotalPrice()  *  (1.0f  +  salesTax);          }   }   What  is  Cohesion?   Cohesion   (Video   Link   -­‐   https://www.youtube.com/watch?v=BkcQWoF5124 )   is   a   measure   of   how  related  the  responsibilities  of  a  class  are.    A  class  must  be  highly  cohesive  i.e.  its  responsibilities   (methods)  should  be  highly  related  to  one  another.  
  • 8. 8   Java  Interview  Questions  –  www.JavaInterview.in       Example  Problem   Example   class   below   is   downloading   from   internet,   parsing   data   and   storing   data   to   database.   The   responsibilities  of  this  class  are  not  really  related.  This  is  not  cohesive  class.   class  DownloadAndStore{          void  downloadFromInternet(){          }                    void  parseData(){          }                    void  storeIntoDatabase(){          }                    void  doEverything(){                  downloadFromInternet();                  parseData();                  storeIntoDatabase();          }   }   Solution This is a better way of approaching the problem. Different classes have their own responsibilities. class  InternetDownloader  {          public  void  downloadFromInternet()  {          }   }     class  DataParser  {          public  void  parseData()  {          }   }     class  DatabaseStorer  {          public  void  storeIntoDatabase()  {          }   }     class  DownloadAndStore  {          void  doEverything()  {                  new  InternetDownloader().downloadFromInternet();                  new  DataParser().parseData();                  new  DatabaseStorer().storeIntoDatabase();          }   }   What  is  Encapsulation?   Encapsulation is “hiding the implementation of a Class behind a well defined interface”. Encapsulation helps us to change implementation of a class without breaking other code.
  • 9. Java  Interview  Questions  –  www.JavaInterview.in   9     Approach  1   In  this  approach  we  create  a  public  variable  score.  The  main  method  directly  accesses  the  score  variable,   updates  it.   public  class  CricketScorer  {          public  int  score;   }     Let’s  use  the  CricketScorer  class.   public  static  void  main(String[]  args)  {   CricketScorer  scorer  =  new  CricketScorer();   scorer.score  =  scorer.score  +  4;   }   Approach  2   In  this  approach,  we  make  score  as  private  and  access  value  through  get  and  set  methods.  However,  the   logic  of  adding  4  to  the  score  is  performed  in  the  main  method.   public  class  CricketScorer  {          private  int  score;            public  int  getScore()  {                  return  score;          }            public  void  setScore(int  score)  {                  this.score  =  score;          }   }     Let’s  use  the  CricketScorer  class.     public  static  void  main(String[]  args)  {   CricketScorer  scorer  =  new  CricketScorer();     int  score  =  scorer.getScore();   scorer.setScore(score  +  4);   }   Approach  3   In  this  approach  -­‐  For  better  encapsulation,  the  logic  of  doing  the  four  operation  also  is  moved  to  the   CricketScorer  class.   public  class  CricketScorer  {          private  int  score;                    public  void  four()  {                  score  +=  4;          }     }     Let’s  use  the  CricketScorer  class.  
  • 10. 10   Java  Interview  Questions  –  www.JavaInterview.in       public  static  void  main(String[]  args)  {   CricketScorer  scorer  =  new  CricketScorer();   scorer.four();   }   Description   In  terms  of  encapsulation  Approach  3  >  Approach  2  >  Approach  1.  In  Approach  3,  the  user  of  scorer  class   does  not  even  know  that  there  is  a  variable  called  score.  Implementation  of  Scorer  can  change  without   changing  other  classes  using  Scorer.   What  is  Method  Overloading?   A method having the same name as another method (in same class or a sub class) but having different parameters is called an Overloaded Method. Example  1   doIt  method  is  overloaded  in  the  below  example:   class  Foo{          public  void  doIt(int  number){                            }          public  void  doIt(String  string){                            }   }   Example  2   Overloading  can  also  be  done  from  a  sub  class.   class  Bar  extends  Foo{          public  void  doIt(float  number){                            }   }   What  is  Method  Overriding?   Creating a Sub Class Method with same signature as that of a method in SuperClass is called Method Overriding. Method  Overriding  Example  1:   Let’s  define  an  Animal  class  with  a  method  shout.   public  class  Animal  {          public  String  bark()  {                  return  "Don't  Know!";          }   }     Let’s  create  a  sub  class  of  Animal  –  Cat    -­‐  overriding  the  existing  shout  method  in  Animal.   class  Cat  extends  Animal  {          public  String  bark()  {  
  • 11. Java  Interview  Questions  –  www.JavaInterview.in   1 1                    return  "Meow  Meow";          }   }   bark method in Cat class is overriding the bark method in Animal class. What  is  an  Inner  Class?   Inner  Classes  are  classes  which  are  declared  inside  other  classes.  Consider  the  following  example:   class  OuterClass  {            public  class  InnerClass  {          }            public  static  class  StaticNestedClass  {          }     }   What  is  a  Static  Inner  Class?   A  class  declared  directly  inside  another  class  and  declared  as  static.  In  the  example  above,  class  name   StaticNestedClass  is  a  static  inner  class.     Can  you  create  an  inner  class  inside  a  method?   Yes.   An   inner   class   can   be   declared   directly   inside   a   method.   In   the   example   below,   class   name   MethodLocalInnerClass  is  a  method  inner  class.     class  OuterClass  {            public  void  exampleMethod()  {                  class  MethodLocalInnerClass  {                  };          }     }   Constructors   Constructor (Youtube Video link - https://www.youtube.com/watch?v=XrdxGT2s9tc ) is invoked whenever we create an instance(object) of a Class. We cannot create an object without a constructor. If we do not provide a constructor, compiler provides a default no-argument constructor. What  is  a  Default  Constructor?   Default Constructor is the constructor that is provided by the compiler. It has no arguments. In the example below, there are no Constructors defined in the Animal class. Compiler provides us with a default constructor, which helps us create an instance of animal class.   public  class  Animal  {          String  name;            public  static  void  main(String[]  args)  {  
  • 12. 12   Java  Interview  Questions  –  www.JavaInterview.in                      //  Compiler  provides  this  class  with  a  default  no-­‐argument  constructor.                  //  This  allows  us  to  create  an  instance  of  Animal  class.                  Animal  animal  =  new  Animal();          }   }   How  do  you  call  a  Super  Class  Constructor  from  a  Constructor? A constructor can call the constructor of a super class using the super() method call. Only constraint is that it should be the first statement i Both example constructors below can replaces the no argument "public Animal() " constructor in Example 3. public  Animal()  {          super();          this.name  =  "Default  Name";   }   Can  a  constructor  be  called  directly  from  a  method?     A constructor cannot be explicitly called from any method except another constructor. class  Animal  {          String  name;            public  Animal()  {          }            public  method()  {                  Animal();//  Compiler  error          }   }   Is  a  super  class  constructor  called  even  when  there  is  no  explicit  call  from  a   sub  class  constructor? If a super class constructor is not explicitly called from a sub class constructor, super class (no argument) constructor is automatically invoked (as first line) from a sub class constructor. Consider the example below: class  Animal  {          public  Animal()  {                  System.out.println("Animal  Constructor");          }   }     class  Dog  extends  Animal  {          public  Dog()  {                  System.out.println("Dog  Constructor");          }   }     class  Labrador  extends  Dog  {          public  Labrador()  {                  System.out.println("Labrador  Constructor");          }  
  • 13. Java  Interview  Questions  –  www.JavaInterview.in   1 3     }     public  class  ConstructorExamples  {          public  static  void  main(String[]  args)  {                  Labrador  labrador  =  new  Labrador();          }   }   Program  Output   Animal Constructor Dog Constructor Labrador Constructor Interface   What  is  an  Interface?   An interface (YouTube video link - https://www.youtube.com/watch?v=VangB-sVNgg ) defines a contract for responsibilities (methods) of a class. How  do  you  define  an  Interface?   An   interface   is   declared   by   using   the   keyword   interface.   Look   at   the   example   below:   Flyable   is   an   interface.   //public  abstract  are  not  necessary   public  abstract  interface  Flyable  {          //public  abstract  are  not  necessary          public  abstract  void  fly();   }   How  do  you  implement  an  interface? We can define a class implementing the interface by using the implements keyword. Let us look at a couple of examples: Example  1   Class  Aeroplane  implements  Flyable  and  implements  the  abstract  method  fly().   public  class  Aeroplane  implements  Flyable{          @Override          public  void  fly()  {                  System.out.println("Aeroplane  is  flying");          }   }   Example  2   public  class  Bird  implements  Flyable{          @Override          public  void  fly()  {                  System.out.println("Bird  is  flying");          }   }  
  • 14. 14   Java  Interview  Questions  –  www.JavaInterview.in       Can  you  tell  a  little  bit  more  about  interfaces?   Variables   in   an   interface   are   always   public,   static,   final.   Variables   in   an   interface   cannot   be   declared   private.   interface  ExampleInterface1  {          //By  default  -­‐  public  static  final.  No  other  modifier  allowed          //value1,value2,value3,value4  all  are  -­‐  public  static  final          int  value1  =  10;          public  int  value2  =  15;          public  static  int  value3  =  20;          public  static  final  int  value4  =  25;          //private  int  value5  =  10;//COMPILER  ERROR   }   Interface  methods  are  by  default  public  and  abstract.  A  concrete  method  (fully  defined  method)  cannot   be  created  in  an  interface.  Consider  the  example  below:   interface  ExampleInterface1  {          //By  default  -­‐  public  abstract.  No  other  modifier  allowed          void  method1();//method1  is  public  and  abstract          //private  void  method6();//COMPILER  ERROR!                    /*//Interface  cannot  have  body  (definition)  of  a  method              //This  method,  uncommented,  gives  COMPILER  ERROR!          void  method5()  {                  System.out.println("Method5");          }            */   }   Can  you  extend  an  interface?   An interface can extend another interface. Consider the example below:   interface  SubInterface1  extends  ExampleInterface1{          void  method3();   }   Class   implementing   SubInterface1   should   implement   both   methods   -­‐   method3   and   method1(from   ExampleInterface1)   An interface cannot extend a class. /*  //COMPILE  ERROR  IF  UnCommented        //Interface  cannot  extend  a  Class   interface  SubInterface2  extends  Integer{          void  method3();   }   */   Can  a  class  extend  multiple  interfaces?  
  • 15. Java  Interview  Questions  –  www.JavaInterview.in   1 5     A class can implement multiple interfaces. It should implement all the method declared in all Interfaces being implemented.   interface  ExampleInterface2  {          void  method2();   }     class  SampleImpl  implements  ExampleInterface1,ExampleInterface2{          /*  A  class  should  implement  all  the  methods  in  an  interface.                If  either  of  method1  or  method2  is  commented,  it  would                  result  in  compilation  error.              */          public  void  method2()  {                  System.out.println("Sample  Implementation  for  Method2");          }            public  void  method1()  {                  System.out.println("Sample  Implementation  for  Method1");          }             }     POPULAR  VIDEOS   Java  Interview  :  A  Freshers  Guide  -­‐  Part  1:  https://www.youtube.com/watch?v=njZ48YVkei0   Java  Interview  :  A  Freshers  Guide  -­‐  Part  2:  https://www.youtube.com/watch?v=xyXuo0y-xoU   Java  Interview  :  A  Guide  for  Experienced:  https://www.youtube.com/watch?v=0xcgzUdTO5M Collections  Interview  Questions  1:  https://www.youtube.com/watch?v=GnR4hCvEIJQ Collections  Interview  Questions  2:  https://www.youtube.com/watch?v=6dKGpOKAQqs Collections  Interview  Questions  3:  https://www.youtube.com/watch?v=_JTIYhnLemA Collections  Interview  Questions  4:  https://www.youtube.com/watch?v=ZNhT_Z8_q9s Collections  Interview  Questions  5:  https://www.youtube.com/watch?v=W5c8uXi4qTw