Suresh Rohan's Blog

This blog is all about Java, J2EE,Spring, Angular, React JS, NoSQL, Microservices, DevOps, BigData, Tutorials, Tips, Best practice, Interview questions, Views, News, Articles, Techniques, Code Samples, Reference Application and much more

Wednesday, May 20, 2015

Object-Oriented Design Principles


Interfaces

In Java, an interface is a set of abstract methods that defines a protocol (i.e., a contract for conduct). Classes that implement an interface must implement the methods specified in the interface. An interface defines a protocol, and a class implementing the interface honors the protocol.

Points to Remember

  • An interface cannot be instantiated
  • An interface can extend another interface. Use the extends.
  • Interfaces cannot contain instance variables. If you declare a data member in an interface, it should be initialized, and all such data members are implicitly treated as “public static final” members.
  • An interface cannot declare static methods. It can only declare instance methods.
  • You cannot declare members as protected or private. Only public access is allowed for members of an interface.
  • All methods declared in an interface are implicitly considered to be abstract. If you want, you 
  • can explicitly use the abstract qualifier for the method.
  • You can only declare (and not define) methods in an interface.
  • An interface can be declared with empty body (i.e., an interface without any members. Such interfaces are known as tagging interfaces (or marker interfaces). Such interfaces are useful for defining a common parent, so that runtime polymorphism can be used. For example, java.util defines the interface EventListner without a body.
  • An interface can be declared within another interface or class; such interfaces are known as nested interfaces.
  • Unlike top-level interfaces that can have only public or default access, a nested interface can be declared as public, protected, or private.


Abstract Classes vs. Interfaces


Choosing Between an Abstract Class and an Interface

  • If you are identifying a base class that abstracts common functionality from a set of related classes, you should use an abstract class. If you are providing common method(s) or protocol(s) that can be implemented even by unrelated classes, this is best done with an interface.
  • If you want to capture the similarities among the classes (even unrelated) without forcing a class relationship, you should use interfaces. On the other hand, if there exists an is-a relationship between the classes and the new entity, you should declare the new entity as an abstract class.

Object Composition

the composite object shares has-a relationships with the containing objects, and the underlying concept is referred to as object composition.

Composition vs. Inheritance


No comments:

Post a Comment