You are on page 1of 14

Interface concepts 1: Why use interfaces to develop Java applications?

A: It is advisable to design relatively large applications using interfaces because it makes the whole system easier to modify, extend and integrate new features. To start with you may only have one implementation of a given interface, but if you find you need slightly different behaviour in special circumstances, you only need write a class that conforms to one of the existing interfaces and it will drop in place without major modifications. Interfaces also allow you to adapt a class from a different hierarchy to work in an existing application. The class only needs to declare it implements the interface, provide the necessary methods and it can be integrated directly as if it were created for the job. 2: I still don't get why I should use interfaces! A: When you first start working with Java interfaces it may seem like extra work without much pay-back, you have to write an empty interface definition and also write concrete methods to implement them. There is no great advantage when you are working with relatively small scale, stand-alone applications for a single purpose. Most people first recognise the need for interfaces when they work with Java API packages that require interface implementations to work effectively, particularly the old-style Abstract Windowing Toolkit (AWT), Swing and Java threads. With Swing you must implement the ActionListener interface to respond to button clicks, for example. The more you implement Java API interfaces for specific purposes the more you will recognise when interfaces are appropriate in your own applications and start to appreciate the benefits. AWT and Swing are strong examples of Java interface use because Graphical User Interface (GUI) classes can implement listener interfaces to handle their own click or status events. In this case, the use of an interface means no extra class definition. public class ListeningFrameExample extends JFrame implements WindowListener { // Application methods // Example WindowListener method public void windowIconified(WindowEvent e) { // Handle window minimised events }

// Other WindowListener methods }

AWT and Swing event handler interfaces like ActionListener only have one method, so can easily be implemented by anonymous inline class definitions, split over several lines in the example below. JButton button = new JButton("Example Button"); button.addActionListener( new ActionListener() { actionPerformed(ActionEvent ae) { // Handle the action } } );

The anonymous class is instantiated using the new keyword followed by the name of the interface with parentheses, as if the interface name is the name of a concrete class. The declaration of the single actionPerformed() method follows, enclosed in curly braces. The close parenthesis on the last line is paired with the opening parenthesis of the addActionListener() method call on the first line; it encloses the whole anonymous class definition and must be followed by a semi-colon. 3: What is the difference between interfaces and inheritance? A: Interfaces and inheritance are closely related in Java. In short, when a class implements an interface it inherits the essential behavioural characteristics of the interface. An instance of the class can be treated the same as any other class that implements the interface. In this case, the implements keyword creates the inheritance relationship between an interface and a class. The interface is a largely abstract model, it defines what is required to be a class of that type in terms of the methods it must provide. A class does not inherit any specific behaviour from an interface, a programmer is free to implement interface methods as they choose. So long as they match the interface method signatures a class inherits the ability to act as or behave like any other implementation class. Interface inheritance creates polymorphism because any class that implements an interface can be cast to that type and used interchangeably with any other in variables and method arguments.

4: But interfaces are implemented by classes, why bother? A: When you compare interfaces with standard class hierarchies there are obvious similarities, especially compared with an entirely abstract class. Both interfaces and abstract classes can be extended and extra abstract methods added. The nature of inheritance means that sub-classes and sub-interfaces are type-compatible with their parents. The use of interfaces in Java is partly a design compromise to support a limited form of multiple inheritance. Purely abstract interfaces enable classes to implement multiple interfaces and extend a superclass within the general constraints of the Java language and runtime environment. The separation of interfaces from classes means it is also possible to compose Java types that are loosely coupled or entirely detached from class hierarchies, which makes them flexible to change. For example, a class may implement the java.util.List interface by encapsulating and adapting a Vector, to make a thin wrapper around the Vector without extending the class. At a later date you can switch the encapsulated Vector to an ArrayList, LinkedList or some other custom implementation without affecting clients of the class. 5: How come methods in interfaces are not defined? A: An interface represents a Java type, a concept of a set of Java classes that behave in a particular way such that any one could be used in place of another. It may help to think of a Java interface as a blueprint, plan or model that says, write a class that has these methods. An interface describes what a Java class must do, but doesn't say how it should be done, that's why interface methods have no code body. A Java programmer is free to code an interface however they choose, so long as their methods have the same names, arguments and return types as the interface. That flexibility enables programmers to write or adapt many different classes to fulfil a particular interface. 6: What is the difference between abstract classes and interfaces? A: A Java interface is a definition of a class type without any concrete implementation. Typically, an interface consists of one or more method signatures that a subclass must fulfil to conform to the type. All their methods are abstract and interfaces cannot be instantiated. 7: Why use interfaces instead of abstract classes? A: The key difference between abstract class and interface based inheritance is that concrete classes are bound to a single abstract class hierarchy, they are tightly coupled

and cannot extend any other class. This makes it difficult to create general purpose component classes that can be re-used in different packages. Interface based inheritance does not create a binding to a specific class hierarchy, so concrete classes can inherit the type characteristics of several interfaces without limiting their scope for re-use. Concrete classes can implement multiple interfaces and extend an abstract class, but it is best to minimise class inheritance as far as possible to preserve lexibility. 8: What's the difference between an interface and an API? A: An Application Programming Interface (API) is the collection of all the public methods and fields that belong to a set of classes, including its interface types. The API defines the way that developers can use the classes in their own Java program, just by importing the relevant classes and writing statements that instantiate the classes and call their public methods and fields. A Java interface declares a type of Java object without a concrete implementation. Interfaces are defined in a compilation unit like a standard Java class and the methods they declare are implicitly part of an Application Programming Interface. Interfaces are used to help define generic structural components in an API, a reference type for concrete implementations, and an extension mechanism for programmers who use the API. 9: Is an API a help document? A: An Application Programming Interface (API) is a way to describe a collection, library or toolkit of Java software that can be used as part of new Java programs. The name Application Programming Interface refers to the components in a packaged collection of Java programs and the special properties and behaviour that they can provide in a Java program. The classes in the Java networking package enable programmers to get information from the Internet, for example. The publicly accessible Java classes, properties and methods in this collection are called the java.net API. Ideally a Java software library should be distributed with a set of help documents that describe its API and explain how Java programmers should use the components in their own programs. These documents can be generated from specially formatted JavaDoc comments embedded in the code but they only describe the API, they are not the API itself. Interface use 10: When should I use an interface?

A: If you are not used to using interfaces in your Java programs you are most likely to recognise the need when you are refactoring an existing application to add a new feature or support a new input or output format. When you think about how to reorganise the program it may be difficult to see where to make the changes, the class hierarchy may seem tangled, or it feels like a new format doesn't fit in neatly. A strong sign that you need to introduce an interface is that you have very similar code in separate classes and you can't re-arrange the classes to inherit this behaviour from a common superclass. When you recognise these characteristics in a system, you should list the behaviour the problem objects need to have so that the main path of the program can process them in the same way. Separate this Processable behaviour in an interface and keep the type-specific behaviour in the classes that need to be processed. Where you see duplicate code in the processable classes, move it up the hierarchy and perhaps head it with an AbstractProcessable class. That should leave the type-specific classes to implement the Processable interface, possibly extend the AbstractProcessable class, and focus the main content of the class on its core, distinct behaviour. A Processable interface defines the type of things that can be processed in a particular way, a set of data that can be rendered as a Web page, for example. An AbstractProcessable superclass may implement the Processble interface and provide some concrete methods for subclasses to use, such as a cleanUpData() method, for example. Concrete ProcessableSpreadsheet, ProcessableDocument and ProcessableReport classes can extend the AbstractProcessable class and implement the Processable interface methods. Finally, an HTMLRenderer class can define a render(Processable) method that accepts any of classes above that implement the Processable interface to generate HTML output.

The main path of your application will need to be adapted to declare and cast these objects as Processable types, but that will mean any other Processable type can more easily be added to the system in future. 11: Where should I use interfaces in my application? A: Partly that's a question that depends on the nature of your application, its overall structure and how it integrates with the Java API and third party libraries. Interfaces can be used in most areas of application development, so they could be used in any part of the system. The main things to look out for are cases where several different things need to be treated in a similar way, an interface can consolidate the common behaviour of a set of classes so that your application code can process them interchangably.

12: When should I use abstract classes rather than interfaces? A: Abstract classes are often used to provide methods that will be common to a range of similar subclasses, to avoid duplicating the same code in each case. Each subclass adds its own features on top of the common abstract methods. 13: How do we use interfaces as variables? A: Java is a strongly typed language, which means that all variables and method arguments must be declared to be a particular type. The references assigned to variables and passed to methods must match their declared type, or be cast to them, to maintain the type safety of the system. Java types fall into 3 categories: Primitive types Including byte, boolean, char, int and other numerics. Object types Including built-in API classes and programmer defined classes. Interface types Types declared by interfaces and implemented by concrete classes.

Interfaces cannot be instantiated in their own right, but the concrete classes that implement them are type-compatible. That means that any class that implements the java.util.List interface can be assigned to a variable of that type, for example. // List interface // Vector implements List List list = new Vector();

When an instance of a class is assigned to an interface type variable in this way, you can safely call any interface methods on the variable. This is an example of polymorphism in Java. A Vector has its own properties and methods, but when assigned to a List type variable, it is treated as a List and can be passed to other methods that require a List type argument.

How to define an interface 14: Should I use a public access modifier for interface methods? A: Java interface methods are always implicitly public, even if they belong to nested interfaces. Non-public modifiers are not valid or necessary for interface methods, so

the compiler should fail and warn you in this case. Nested interfaces may be declared protected or private.

15: Non-public modifiers can be used for nested interfaces! A: Interface methods must be public, the compiler will fail and issue a warning if interface methods are declared protected or private, even in nested interfaces. Nested interfaces themselves may be declared protected or private. 16: Can we create a Java class inside an interface? A: Yes, classes can be declared inside interfaces. This technique is sometimes used where the class is a constant type, return value or method argument in the interface. When a class is closely associated with the use of an interface it is convenient to declare it in the same compilation unit. This proximity also helps ensure that implementation changes to either are mutually compatible. A class defined inside an interface is implicitly public static and operates as a top level class. The static modifier does not have the same effect on a nested class as it does with class variables and methods.

17: Can an interface extend a class? A: In Java an interface can only extend another interface, called a super-interface. This is an inheritance relationship like superclass-subclass; the sub-interface inherits all the constant variables and abstract methods defined in the super-interface and can add its own. Since an interface may have a static class defined within it, it is possible for a class in a sub-interface to extend a class in a super-interface, but that is a different thing entirely. In this case the extension of nested classes is no different from standard extends inheritance except the hosts of the classes are interfaces. There is no mixture of class and interface extension. 18: Can an interface extend an abstract class? A: In Java an interface cannot extend an abstract class. An interface may only extend a super-interface. However, an abstract class can implement an interface. It may help

to think of interfaces and classes as separate lines of inheritance that only come together when a class implements an interface, the relationship cannot be reversed. 19: Can an interface be declared final? A: It is not permitted to declare an interface as final, it will cause a compilation error. This is a Java language design decision. Interface types are intended to be implemented and can be extended without restriction. Some regard this free extensibility as a flaw in the language design because there are cases where it would be useful to restrict the broader use of an interface. In the current scheme it does not make sense to declare an interface final because it would imply it could not be extended and possibly not implemented, which would not be useful. How to implement an interface 20: Can we create an object for an interface? A: Yes, the most common scenario is to create an object implementation for an interface, although they can be used as a pure reference type. Interfaces cannot be instantiated in their own right, so it is usual to write a class that implements the interface and fulfils the methods defined in it. public class Concrete implements ExampleInterface { ... } 21: Is more than one interface allowed? A: Yes, a class can implement multiple interfaces, this is an effective way to achieve multiple inheritance in Java. A class can only extend one superclass. 22: Is it necessary to implement all interface methods? A: It is not necessary for a class that implements an interface to implement all its methods, but in this case the class must be declared abstract. In this respect the implementation of an interface is similar to the extension of an abstract class. The implementation of the interface methods can be deferred through any number of abstract subclasses, but at some point you should create concrete implementations. In fact, its a sign there may be something wrong with your code design if you defer interface implementation in more than one or two subclasses. 23: How is the implements keyword different from extends?

A: The implements keyword is used when a class explicitly fulfils an interface definition with concrete method implementations for its abstract method signatures. A single class can implement more than one interface, but must be declared abstract if it does not implement all interface methods. The extends keyword is used when an interface inherits the type definition specified in a super-interface, or a class inherits from a superclass. A class can only extend a single superclass but may also implement one or more interfaces. When an interface extends a super-interface it is not required or permitted to implement any of its abstract methods since the sub-interface must be abstract itself.

24: What if two interface methods clash in implementation? A: If two interfaces have the same method signature, they effectively declare the same method regardless of any other intentions. Any concrete class that implements both interfaces can only provide one implementation of a given method signature, so there is no ambiguity about how the Java compiler deals with this case, only a potentially difficult design decision. If two interface methods have a clash over their method signatures and intended behaviour, it would preferable to rename one of the interface methods to indicate a more distinct purpose. 25: When interfaces clash, which method answers the call? A: In this case neither interface answers the method call, thus it is not a problem. The interface methods must be implemented by a concrete class and it is the single concrete method in the implementation class that will handle the call. Marker interfaces 26: What is a marker interface? A: Marker interfaces do not declare any required methods, but their implementation signifies compatibility with certain operations. The java.io.Serializable interface is a typical marker interface, classes must implement this interface in order for their instances to be serialized and de-serialized. 27: How do marker interfaces affect the behaviour of classes? A: Marker interfaces do not affect the classes that implement them through their behaviour, they cannot since there are no required methods, they only mark the class

by identifying it as a Java type that conforms to the interface. In the classic example, methods that serialize data can check that a class can be serialized by its implementation of the Serializable interface. 28: Are there any marker interfaces that have methods? A: No, the definition of a marker interface is that it contains no behavioural definitions, so there can be no marker interface that has methods. Marker interfaces are concerned with being a certain type rather than behaving as a type does. 29: Can we implement a marker interface? A: Yes, marker interfaces can be implemented, just add the implements keyword and the name of the interface to your class declaration, as below. public class ExampleSerializable implements Serializable { // No interface methods to implement } 30: Why do we need to implement the Serializable interface? A: In some respects marker interfaces such as Serializable are like a prompt or reminder to programmers that we must implement the interface to get the results we need; most importantly we must ensure that the class is truly serializable. A class must implement the Serializable interface else any attempt to serialize an instance will throw a NotSerializableException. However, it is the programmer's responsibility to ensure that an instance can physically be serialized and de-serialized in a meaningful way, so that the object's original state can be fully restored. That can be a complex task, especially when a class has field types that are final and do not implement the Serializable interface, hence the interface is a marker that special measures need to be taken. Interface constants 31: Do interfaces have member variables? A: Interfaces may have variable fields but they are implicitly final and static. Interface variables are inherited by any class that implements the interface and are also available as public static variables of the interface. In effect, interface variables are constants that are available to all implementations and may be used as key references for method arguments, for example.

32: Are you sure you can declare member variables in an interface? A: Yes, it is definitely possible to declare member variables in an interface, though it may help to call them static member variables. Interface variables are implicitly static, even if you omit the static keyword they will be compiled and treated as public static final constants. You cannot declare an instance variable in a Java interface. 33: Why are interface variables public static final? A: The short answer is that interface variables are intended to be Java constants, which means they must have these universal and un-changable properties. Interface variables are implicitly public because interfaces are intended to provide an Application Programming Interface (API) that is fully accessible to Java programmers to reference and implement in their own applications. Since an interface may be used in Java packages that are different from their own, public visibility ensures that program code can access the variable. Interface variables are static because Java interfaces cannot be instantiated in their own right; the value of the variable must be assigned in a static context in which no instance exists. The final modifier ensures the value assigned to the interface variable is a true constant that cannot be re-assigned by program code. 34: Interface variables can be overridden, right? A: No, interface variables are constants that cannot be overridden. They are inherited by any class that implements an interface. 35: This interface variable is assigned in a constructor! A: In this case a final instance variable in a class is declared as an interface type, which is different from a constant field in an interface. The example below shows a List type assigned a final variable in a class constructor. Any object that fulfils the List interface can be passed to the class constructor and assigned to its final instance variable. The final variable cannot be changed after instantiation. 36:Why is interface useful? Interfaces are useful for the following:

Capturing similarities among unrelated classes without artificially forcing a class relationship. Declaring methods that one or more classes are expected to implement. Revealing an object's programming interface without revealing its class.

An interface is a contract in the form of a collection of method and constant declarations. When a class implements an interface, it promises to implement all of the methods declared in that interface. Interfaces are useful for capturing similarities among unrelated classes without artificially forcing a class relationship, declaring methods that one or more classes are expected to implement and revealing an object's programming interface without revealing its class. Java uses interface and abstract Class to define interfaces. 37: When should you use an abstract class, when an interface, when both? Abstract class definition begins with the keyword "abstract" keyword followed by Class definition. An Interface definition begins with the keyword "interface". 38:What are the disadvantages of Interfaces? The problem with an interface is, if you want to add a new feature (method) in its contract, then you MUST implement those method in all of the classes which implement that interface. However, in the case of an abstract class, the method can be simply implemented in the abstract class and the same can be called by its subclass Interfaces are slow as it requires extra indirection to to find corresponding method in in the actual class. Abstract classes are fast. 39:If interface & abstract class have same methods and those methods contain no implementation, which one would you prefer? Obviously one should ideally go for an interface, as we can only extend one class. Implementing an interface for a class is very much effective rather than extending an abstract class because we can extend some other useful class for this subclass 40:Can Abstract Class have constructors? Can interfaces have constructors? Abstract class's can have a constructor, but you cannot access it through the object, since you cannot instantiate abstract class. To access the constructor create a sub class and extend the abstract class which is having the constructor. Example public abstract class AbstractExample { public AbstractExample(){ System.out.println("In AbstractExample()"); } } public class Test extends AbstractExample{ public static void main(String args[]){ Test obj=new Test();} }

41:Can you make an instance of an abstract class? Abstract classes can contain abstract and concrete methods. Abstract classes cannot be instantiated directly i.e. we cannot call the constructor of an abstract class directly nor we can create an instance of an abstract class by using Class.forName().newInstance() (Here we get java.lang.InstantiationException). However, if we create an instance of a class that extends an Abstract class, compiler will initialize both the classes. Here compiler will implicitly call the constructor of the Abstract class. Any class that contain an abstract method must be declared abstract and abstract methods can have definitions only in child classes. By overriding and customizing the abstract methods in more than one subclass makes Polymorphism and through Inheritance we define body to the abstract methods. Basically an abstract class serves as a template. Abstract class must be extended/subclassed for it to be implemented. A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated. Abstract class is a class that provides some general functionality but leaves specific implementation to its inheriting classes. Example of Abstract class: abstract class AbstractClassExample{ protected String name; public String getname() { return name; } public abstract void function(); } Example: Vehicle is an abstract class and Bus Truck, car etc are specific implementations No! You cannot make an instance of an abstract class. An abstract class has to be sub-classed. If you have an abstract class and you want to use a method which has been implemented, you may need to subclass that abstract class, instantiate your subclass and then call that method. 42:What does it mean that a method or class is abstract? An abstract class cannot be instantiated. Only its subclasses can be instantiated. A class that has one or more abstract methods must be declared abstract. A subclass that does not provide an implementation for its inherited abstract methods must also be declared abstract. You indicate that a class is abstract with the abstract keyword like this: public abstract class AbstractClass Abstract classes may contain abstract methods. A method declared abstract is not actually implemented in the class. It exists only to be overridden in subclasses. Abstract methods may only be included in abstract classes. However, an abstract class is not required to have any abstract methods, though most of them do. Each subclass of an abstract class must override the abstract methods of its superclasses or itself be declared abstract. Only the methods prototype is provided in the class definition. Also, a final method can not be abstract and vice versa. Methods specified in an interface are

implicitly abstract. . It has no body. For example, public abstract float getInfo(

You might also like