Put your text ad here
WestNIC provides reliable web hosting services
Free software downloads and drivers download resources
25% off cpanel web hosting and reseller hosting deals. Promo: codestyle25off
This FAQ is part of the Code Style Help and FAQ section. Join our premium content service for full access all FAQs, or choose the single FAQ by email option for premium answers.
Serializable interface?
public access modifier for interface methods?
final?
public static final?
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.
Actions: Follow-up, clarify or correct this answer. Submit a new question.
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. In effect, all their methods are abstract, and interfaces cannot be instantiated.
… premium content omitted
Get full access to all FAQs, subscribe now for $40
What is the difference between abstract classes and interfaces?
Actions: Follow-up, clarify or correct this answer. Submit a new question.
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 methods public 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 elements in an API, a reference type for concrete implementations, and an extension mechanism for programmers who use the API.
Actions: Follow-up, clarify or correct this answer. Submit a new question.
A: Marker interfaces are those which do not declare any required methods, but signify their compatibility with certain operations. The java.io.Serializable interface is a typical marker interface. It does not contain any methods, but classes must implement this interface in order to be serialized and de-serialized.
Actions: Follow-up, clarify or correct this answer. Submit a new question.
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.
Actions: Follow-up, clarify or correct this answer. Submit a new question.
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.
Actions: Follow-up, clarify or correct this answer. Submit a new question.
A: An interface typically represents something that is "Processable" in a particular way, an example would be a Soluble type that has an interface method void dissolve(Solvent). Marker interfaces don't have any interface methods, they usually signify a property or state that any Java class may have that cannot be defined by a method signature. An example would be an Immutable interface, since a fundamental characteristic of immutable classes is the absence of mutator methods, as below.
… premium content omitted
Get full access to all FAQs, subscribe now for $40
Can you show an example marker interface?
Actions: Follow-up, clarify or correct this answer. Submit a new question.
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 re-organise 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.
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.
Actions: Follow-up, clarify or correct this answer. Submit a new question.
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.
… premium content omitted
Get full access to all FAQs, subscribe now for $40
When should I use abstract classes rather than interfaces?
Actions: Follow-up, clarify or correct this answer. Submit a new question.
A: To illustrate multiple inheritance, consider a bat, which is a mammal that flies. We might have two interfaces: Mammal, which has a method suckleInfant(Mammal), and Flyer, which has a method fly(). These types would be declared in interfaces as below...
… premium content omitted
Get full access to all FAQs, subscribe now for $40
Can you give an example of multiple inheritance with interfaces?
Actions: Follow-up, clarify or correct this answer. Submit a new question.
A: It may help to discuss an example using birds: an interface called Avian, a superclass FlyingBird that implements Avian and two concrete classes: Parrot and Penguin. Parrot extends FlyingBird, so is implicitly an Avian type, but Penguin does not, it only implements Avian. The examples below work through all possibilities, passing references to methods soundBirdCall(FlyingBird) and displayPlumage(Avian).
… premium content omitted
Get full access to all FAQs, subscribe now for $40
What are the rules for passing subclasses for method arguments?
Actions: Follow-up, clarify or correct this answer. Submit a new question.
public access modifier for interface methods?
A: Java interfaces are used to define a public Application Programming Interface (API) for classes to implement, so a public modifier is redundant in this context. Non-public modifiers are not valid for interfaces, so the compiler should fail and warn you in this case.
Actions: Follow-up, clarify or correct this answer. Submit a new question.
A: In Java an interface cannot extend an abstract class. An interface may only extend a super-interface. And an abstract class may 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.
Actions: Follow-up, clarify or correct this answer. Submit a new question.
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 mean it could not be implemented or extended; since interfaces cannot be instantiated in their own right a final interface would be a functional dead end.
Actions: Follow-up, clarify or correct this answer. Submit a new question.
A: Interfaces may have member variables, but these are implicitly final and static. Interface variables are inherited by any class that implements the interface and 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.
Actions: Follow-up, clarify or correct this answer. Submit a new question.
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.
Actions: Follow-up, clarify or correct this answer. Submit a new question.
A: The way that interface constants are declared is arbitrary, whether you use the full public static final modifiers or none at all the compiled code will be the same. Strictly the modifiers are redundant and the Java Language Specification states that it is "strongly discouraged as a matter of style, to redundantly specify the public modifier for interface methods".
Java code style is intended to help the reader without stopping to think too hard. The convention of setting constant variable names in upper case letters with underscore separators, CONSTANT_NAME, is recommended and likely to be a stronger guide to the nature of the constant.
Actions: Follow-up, clarify or correct this answer. Submit a new question.
A: Your interface constant declaration is wrong for two reasons. Firstly, the keyword interface cannot be used in variable declarations, only in the enclosing interface declaration itself.
public interface Example {
// API declarations
}
Secondly, the type of the variable must match that of the value that is assigned to it; an int cannot be assigned a String value. Standard Java code style is to give your interface constant an uppercase variable name with words separated by underscores.
public static final String EXAMPLE = "Constant example";
Actions: Follow-up, clarify or correct this answer. Submit a new question.
A: Yes, it is always necessary to create an object implementation for an interface. Interfaces cannot be instantiated in their own right, so you must write a class that implements the interface and fulfil all the methods defined in it.
public class Concrete implements ExampleInterface {
...
}
Actions: Follow-up, clarify or correct this answer. Submit a new question.
A: The code you are looking at declares an inline anonymous class that implements an interface, which has a similar effect. This declaration does not instantiate the interface, but defines the type of the anonymous class, which has no name of its own. This approach is often used in AWT or Swing applications where a class is required to fulfil a minimal interface and it is not necessary to retain a reference to it by assignment.
… premium content omitted
Get full access to all FAQs, subscribe now for $40
This code seems to be instantiating an interface!
Actions: Follow-up, clarify or correct this answer. Submit a new question.
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.
Actions: Follow-up, clarify or correct this answer. Submit a new question.
| Front-end FAQs | Back-end FAQs | Learning Java |
|---|---|---|
About us: site help, text ads, sponsored links and premium content FAQs.