Put your text ad here
WestNIC provides reliable web hosting services
Web hosting directory, find affordable web hosting
Fastwebhost offers cheap web hosting & reseller hosting services
This FAQ is part of the Code Style Help and FAQ section. Join our premium content service for full access all FAQ answers.
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: The main reason to use an abstract class rather than an interface is because abstract classes can carry a functional “payload” that numerous subclasses can inherit and use directly. Interfaces can define the same abstract methods as an abstract class but cannot include any concrete methods.
In a real program it is not a question of whether abstract classes or interfaces are better, because both have features that are useful. It is common to use a mixture of interface and abstract classes to create a flexible and efficient class hierarchy that introduces concrete methods in layers. In practical terms it is more a question of the appropriate point in the hierarchy to define “empty” abstract methods, concrete methods and combine them through the extends and implements keywords.
The example below compares a “Spectrum” type defined by an interface and an abstract class and shows how the abstract class can provide protected methods that minimise the implementation requirements in its subclasses.
… full answer hidden
Premium members click below for full answer
Why use an abstract class instead of an interface?
A: An abstract class without any abstract methods should be a rare thing and you should always question your application design if this case arises. Normally you should refactor to use a concrete superclass in this scenario.
One specific case where abstract class may justifiably have no abstract methods is where it partially implements an interface, with the intention that its subclasses must complete the interface. To take a slightly contrived motoring analogy, a Chassis class may partially implement a Vehicle interface and provide a set of core methods from which a range of concrete Vehicle types are extended. Chassis is not a viable implementation of a Vehicle in its own right, so a concrete Car subclass would have to implement interface methods for functional wheels, engine and bodywork.
A: One of the design principles of Java inheritance is to create superclass methods that can be used by one or more subclasses, this avoids duplication of code and makes it easier to amend. The same principle holds with abstract classes that are fulfilled by numerous subclasses.
One useful technique with abstract classes is that a concrete method may be defined in anticipation of abstract methods being fulfilled in its subclasses. In the example below the AbstractShape class has a concrete printArea() method that calls the abstract getArea() method. Subclasses inherit the printArea() method and must implement the getArea() method to stand as concrete classes.
… full answer hidden
Premium members click below for full answer
What's the use of concrete methods in abstract classes?
A: Inheritance is fundamental to the Java programming language and it is vital that any class should be able to extend another, no matter how many superclasses it has. Abstract classes should be no different, so long as the subclass is abstract too you can have very extended hierarchies of abstract classes. Though it is possible to have many levels of inheritance, you should question your application design if you have more than 2 or 3 successive abstract classes without a concrete implementation.
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: The answer given is definitely correct. It is not common, but an abstract class may have no methods at all and still compile successfully, such as the example below.
public abstract class AbstractNoMethods {
// Empty
}
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 error. 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". However, an abstract class can have static variables and methods, which can be accessed directly using the standard dot notation, e.g. AbstractExample.staticMethod(). It follows that static methods must be concrete.
A: Yes, the examples below show how a static field and a static method in an abstract superclass are called in a concrete subclass using the dot notation. The subclass inherits the NULL_KEY field so the dot notation is not strictly necessary for this public field reference but shows the syntax that should be used in unrelated classes.
… full answer hidden
Premium members click below for full answer
Can you show some static calls to abstract classes?
A: The rule against static abstract methods is fundamentally a Java language design decision, which is not explained in the Java Language Specification. The abstract inheritance and implementation scheme is concerned with forming a structured collaboration of classes with deferred implementation of its abstract instance methods. This scheme can be verified at compile time to ensure it is safe at runtime.
Static methods must be concrete because they are attached to a specific host class and must be available to execute in a static context, when no object instance exists. It is not possible to assign an implementation to a static method at runtime, there is no mechanism to do that in Java.
It is also worth noting that static methods cannot be overridden by a subclass in Java. Static methods with the same signature effectively hide the superclass method. The concept of implementing a static method in a subclass would fail for the same reason, the concrete implementation would be attached to the “wrong” host.
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: If you attempt to compile a class with a private abstract method it will fail with the message “illegal combination of modifiers: abstract and private”. An abstract method must be declared with implicit package visibility or with the protected or public keywords. The fundamental principle is that an abstract method must be visible to any potential subclass. If an abstract method was private it would not be visible to any subclass and could not be implemented.
The concrete implementation of the abstract method in a subclasses must have the same level of visibility or greater. If an abstract method has package visibility, its subclass implementations must have the same, protected or public visibility. If an abstract method has protected visibility, concrete implementations must have the same or public visibility. If an abstract method has public visibility the concrete versions must also be public.
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.
… full answer hidden
Premium members click below for full answer
How can I call a concrete instance method on an abstract class?
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.
… full answer hidden
Premium members click below for full answer
Can you give an example of an abstract class?
A: In Java it is possible to execute the static methods of abstract classes, since an object instance is not required in this context.
public abstract class AbstractStaticMethod {
public static void doSomething() {
System.out.println("Static method called.");
}
public static void main(String[] args) {
doSomething();
}
}
Since abstract classes cannot be instantiated in their own right, no instance methods can be called except through their subclasses.
A: This may sound odd, but an abstract class may have constructors, but they cannot be used to instantiate the abstract class. If you write statements to call the constructor the compiler will fail and report the class is "abstract; cannot be instantiated".
public abstract class AbstractConstructor {
public AbstractConstructor() {
// Statements
}
public AbstractConstructor(final int size) {
// Statements
}
public static void main(String[] args) {
// Not permitted
// AbstractConstructor instance1 = new AbstractConstructor();
// Not permitted either
// AbstractConstructor instance2 = new AbstractConstructor(4);
}
}
Constructors in abstract classes are designed only to be used by their subclasses using a super() call in their own constructors. Though the abstract class cannot stand as an instance in its own right, when its abstract methods are fulfilled by a subclass, its constructors can be called upon to deliver stock template-like initialisation behaviour, for example.
public class ConcreteSubclassSuperconstructor extends AbstractConstructor {
private static final int INDEX = 4;
public ConcreteSubclassSuperconstructor() {
super(INDEX);
}
}
| Front-end FAQs | Back-end FAQs | Learn Java |
|---|---|---|
About us: site help, text ads and premium content FAQs.