CSS font stacks, media style sheets & web standards

Your banner ad here

WestNIC provides reliable web hosting services

25% off cpanel web hosting and reseller hosting deals. Promo: codestyle25off

Site navigation below

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.

Understanding abstract classes

Q: When should I use abstract methods?

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.

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: Must a superclass be abstract or concrete?

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.

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: Must abstract classes contain at least one abstract method?

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.

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: You're wrong, abstract classes must have an abstract method!

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
}
      

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: Why do we need abstract classes with no abstract methods?

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.

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: How can an abstract method be inherited?

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.

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: Do I have to implement all abstract methods?

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.

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Abstract method design constraints

Q: Can a static method be abstract?

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.

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: Why can't abstract methods be declared static?

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.

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: Why can't an abstract method be declared private?

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.

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Abstract classes and methods

Q: How can I call a concrete instance method on an abstract class?

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.

premium content omitted

Premium Content: Follow this link for subscription information Get full access to all FAQs, subscribe now for $40
How can I call a concrete instance method on an abstract class?

Get the answer to this FAQ by email Get the full answer to this FAQ by email for $2.99
within 24 hours of clearance by PayPal.

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: Can you give an example of 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.

premium content omitted

Premium Content: Follow this link for subscription information Get full access to all FAQs, subscribe now for $40
Can you give an example of an abstract class?

Get the answer to this FAQ by email Get the full answer to this FAQ by email for $2.99
within 24 hours of clearance by PayPal.

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: Can I call a static method on 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.

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: Can I declare a constructor for an abstract class?

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);
    }
}
      

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Add this page to your chosen social bookmarking service

Style warning - please read

Home · CSS · Java · Javascript · HTML · Help · Log