Place your text ad here.
World class data recovery software and renowned raid recovery services
WestNIC provides reliable web hosting services
Free software downloads and drivers download resources
Ahosting.biz reseller hosting, managed dedicated server with 24/7 support
This FAQ is part of the Code Style Help and FAQ section. Use the help request form below if your question is not answered here, but make sure you are asking the right question first.
void instead of an object?
A: One of the key benefits of inheritance is to minimise the amount of duplicate code in an application by sharing common code amongst several subclasses. Where equivalent code exists in two related classes, the hierarchy can usually be refactored to move the common code up to a mutual superclass. This also tends to result in a better organisation of code and smaller, simpler compilation units.
Inheritance can also make application code more flexible to change because classes that inherit from a common superclass can be used interchangeably. If the return type of a method is superclass Example, then the application can be adapted to return any class that is descended from Example.
A: There are two forms of inheritance in the Java language. The standard form of inheritance is by extension; a class declares that it extends another class, or an interface extends another interface. In this case, the sub-class or sub-interface inherits all the fields and methods of its parent.
The second special form of inheritance is where classes declare that they implement an interface, which has more limited consequences. When a class implements an interface, it inherits any fields from the parent as final constants, but must provide its own implementation of the interface methods.
A: The authors of the Java language took a design decision to compromise multiple inheritance with interfaces, the specifics of this decision may be covered in other sources. Practically, multiple inheritance is difficult because of the ambiguities it can create when a class inherits from two superclasses with the same method signature: which version should be called?
More details available to subscribers:
Why doesn't Java support multiple inheritance?
A: The short answer to your question is no, this is one of the limitations of the Java language. However, if you use object composition, it can be relatively easy to fulfil two or more interfaces with adaptor code that passes calls through to the underlying objects.
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.
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...
More details available to subscribers:
Can you give an example of multiple inheritance with interfaces?
A: Inheritance is a design principle in object oriented languages like Java. Inheritance means that classes acquire methods and properties by declaring that they are a sub-class of a class that already has those features. This can significantly improve the efficiency and management of code because methods only need to be written once and can be used by any number of sub-classes.
An abstract class is one that is designed to provide methods or properties to sub-classes like a template. Abstract classes cannot be instantiated in their own right and usually contain abstract methods that sub-classes must implement to complete the intended inheritance program design. For instance, abstract methods may have a concrete method that calls an abstract method, whose implementation varies in each sub-class.
A: When a Java class is imported, the type it represents is made available to the host class to use as if it were contained within the host. The imported class is not "visible" through the public interface of the host unless it is declared to extend it.
More details available to subscribers:
What's the difference between importing and extending a class?
A: Java inheritance has been designed to be universal; any non-final Java class can be extended without any special handling for graphical user interface types. Child classes will directly inherit all non-private fields and methods of the parent, which can be overridden and extended however you choose.
Having said that, graphical user interface classes can be quite complex and rely upon specific method calls to maintain their integrity. Be cautious if you override methods and make sure you check there are no unintended side effects of your changes. If you are not certain of the consequences of your overrides, call the overridden superclass method before your own method statements.
In general, it is safest only to add features to GUI classes or build new structures by composition.
A: To prevent a class from being extended or subclassed include the final modifier in the class declaration statement, as below.
public final class FinalClass {
// Class definition
}
A: So long as a class and its methods are not marked final, a subclass can declare a method with the same signature and its own implementation. A typical example is the String toString() method, which is declared in the Object class. All objects implicitly inherit this method. The default implementation is to output the class name combined with its hash code in hexadecimal. The String class overrides the toString() method to give a Unicode representation of string content of the object. Any other object may override toString() with its own method body, to return its own custom output.
public String toString() {
return "All classes may override non-final methods.";
}
void instead of an object?
A: It will often help to understand the Java language if you create small test classes, compile and run them. If you try to compile this test case, you will find it fails because the method signatures have return types: void and an object reference. In Java, void is a return type and void methods must not return object references.
To override a method, the subclass method must have the same signature as the superclass: return type, method name and arguments. If the return type of the subclass method is different it will fail to compile, "attempting to use incompatible return type".
A: An overridden method in a subclass must take priority over the superclass implementation because a class can only expose one implementation of a particular method signature through its public API. The technique of overriding effectively says "use this special implementation of the method instead of the superclass version".
A: To call a superclass method that has been overridden in a subclass, you must either call the method directly through a superclass instance, or use the super prefix in the subclass itself. From the point of the view of the subclass, the super prefix provides an explicit reference to the superclass' implementation of the method.
// From subclass
super.overriddenMethod();
A: To prevent a specific method from being overridden in a subclass, use the final modifier on the method declaration, which which means "this is the final implementation of this method", the end of its inheritance hierarchy.
public final void exampleMethod() {
// Method statements
}
A: Abstract methods are usually declared where two or more subclasses are expected to fulfil a similar role in different ways. Often the subclasses are required to the fulfil an interface, so the abstract superclass might provide several of the interface methods, but leave the subclasses to implement their own variations of the abstract methods. Abstract classes can be thought of as part-complete templates that make it easier to write a series of subclasses.
For example, if you were developing an application for working with different types of documents, you might have a Document interface that each document must fulfil. You might then create an AbstractDocument that provides concrete openFile() and closeFile() methods, but declares an abstract displayDocument(JPanel) method. Then separate LetterDocument, StatementDocument or InvoiceDocument types would only have to implement their own version of displayDocument(JPanel) to fulfil the Document interface.
A: A superclass may be abstract or concrete, provided the concrete class is not declared final. In both cases, you can add supplementary methods to those inherited from the superclass. To extend abstract classes you must fulfil any abstract methods that are declared by the superclass.
A: No, abstract classes are not required to have any abstract methods, they can simply be marked abstract for general design reasons. An abstract class may contain a full set of functional, integrated methods but have no practical use in its basic form, for example. In other words, they may require extension with additional methods to fulfil a range of different purposes. If the purpose is not specified by abstract method signatures, the range of potential applications for subclasses can be very broad.
A: A subclass inherits all non-private fields and methods of its superclass whether the methods are abstract or have concrete implementations. If a subclass does not implement an abstract method, the subclass must be declared abstract itself. That means that an abstract method can be inherited through numerous abstract classes without any concrete implementation.
A common use of abstract methods is the template design pattern, where the common behaviour of a class hierarchy is defined in a set of concrete methods in an abstract superclass. Those core methods include calls to abstract template methods which must be implemented in concrete subclasses. This makes it relatively easy to implement subclasses and produce type-specific behaviour in each.
A: Yes, it is possible to extend an abstract class without implementing its abstract methods, but in this case the subclass must also be declared abstract. If the subclass is not declared abstract, the compiler will throw an exception. So ultimately it is necessary for any concrete subclass to implement the abstract methods.
A: The abstract keyword cannot be applied to static method declarations. The compiler will reject the class with the error "illegal combination of modifiers".
A: The private and abstract method modifiers do not make sense in combination and the compiler should normally fail with a warning in this case. An abstract method must be overridden by any subclass, but subclasses do not have access to their superclass' private fields, so a private abstract method could never be fulfilled.
A: Declaring a class final is the simplest way to prevent extension, it is not clear why you would want to do it some other way. A more limited way to control overrides without preventing extension is to declare individual methods final.
A: It is only possible to call a concrete method of an abstract class when the method is instantiated through a concrete subclass. The method must also have a public or package visibility modifier that makes it accessible to the calling class. When you call the method on the subclass, it implicitly invokes superclass implementation, as in the example below.
More details available to subscribers:
How can I call a concrete instance method on an abstract class?
A: The Java visibility modifiers are firstly concerned with which classes can access the variables and methods, and secondly with inheritance. If a field or method is marked public or protected they will be accessible in sub-classes too. If they have no explicit visibility modifier, they have an implicit package visibility status, which is accessible to sub-classes in the same package, but not to sub-classes in a different package.
The private visibility keyword means only accessible from the host class, public means any class can read a variable or call a method.
protected modifier for?
A: The Java visibility modifiers are concerned with data hiding and encapsulation, they control which classes and sub-classes can read and write variable values and call methods. The protected visibility modifier means that the field or method is accessible from within the host class itself, and internally to other classes in the same package and subclasses that may be in a different package. Protected fields cannot be accessed through the public API of a class.
The protected modifier is usually used to develop the features of an inheritance hierarchy by sharing access to common variables and methods with subclasses. It offers greater scope for extension than package visibility without creating a public API.
protected method?
A: With this type of question it is often easiest to create a minimal test case and attempt to compile it. In this case you will find that the compiler will fail and issue a warning if you attempt to assign "weaker" access privileges to the overridden methods using private or implicit package private modifiers. The term weaker is slightly misleading in this context; it means that the private and package access modifiers are more restrictive than the parent classes' method, which is not permitted. In short, only protected or public visibility modifiers can be used to override protected methods.
A: Yes, this example of an abstract class hierarchy has a superclass AbstractShape that includes a concrete moveTo(int, int) method that will be inherited by any subclass. It also includes an abstract double getArea() method that must be implemented by any concrete subclass. The implementation of the getArea() method is different in the Circle and Square subclasses.
More details available to subscribers:
Can you give an example of an abstract class?
A: Yes, Java class constructors are assigned access modifiers. If none is explicitly declared, the constructor will implicitly have package visibility, which means it is accessible by the class itself and other classes in the same package only. Constructors may also be assigned private, protected or public access. The choice of constructor visibility modifiers will depend on the nature of your application, but the notes below give some broad principles in each case.
More details available to subscribers:
Can constructors have visibility modifiers?
| Front-end FAQs | Back-end FAQs | Learning Java |
|---|---|---|
See site help for questions about this site, our text ads and sponsored links services.