CSS font stacks & developer FAQs with Web standards

WestNIC provides reliable web hosting services

Fastwebhost offers cheap web hosting & reseller hosting services

Site navigation below

This FAQ is part of the Code Style Help and FAQ section. Join our premium content service for full access all FAQ answers.

What if you were One Percent Better with Java inheritance? Java inheritance FAQ ebook for iPad, Kindle, Nook and Sony Reader

Java inheritance principles

Q: What are the benefits of inheritance?

A: One of the key benefits of inheritance is to minimise the amount of duplicate code in an application by putting common code in a superclass and sharing 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.

Q: Is inheritance applicable for beginners in programming?

A: Inheritance is a good aspect to start learning in Java because it is fundamental to the object oriented approach and the concept is relatively easy to understand. The best way to learn about inheritance in Java is to write two simple test classes where one extends the other, compile and adapt from there to experiment.

public class Superclass {

  // Initial implementation empty
}
    
public class Subclass extends Superclass {

  // Initial implementation empty
}
    

Make sure these classes compile, then adapt. For example, add a simple identification method to the superclass, as below.

… full answer hidden

Premium members click below for full answer
Is inheritance applicable for beginners in programming?

Q: What forms of inheritance are supported by Java?

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 subclass 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.

Q: Can you show examples of Java inheritance?

A: An example of inheritance using the extends keyword would be the java.util.Stack class that extends the Vector class to provide a last-in-first-out stack of Objects. The Stack class uses the same underlying storage facilities provided by the superclass and adds its own, so it “is a” type of Vector and behaves like a specialised “wrapper” around the Vector class. The Stack class adds a boolean empty() method, peek(), pop() and push() methods to manage the stack contents and a search() method to find the index of a given object. All the original methods of the Vector class remain and the Stack can be cast to a Vector as necessary.

… full answer hidden

Premium members click below for full answer
Can you show examples of Java inheritance?

Q: Isn't specialization a form of inheritance?

A: Specialization is an application of inheritance, not a particular form of inheritance. From a technical point of view one can only apply the extends and implements keywords in Java to achieve inheritance; the way that a programmer implements the inheritance scheme affects the nature of super- and sub-class relationships. For example, abstract classes and interfaces are typically used to specify the methods of their subclasses, which is specification. Subclasses often provide special versions of the more general superclass, that is specialization.

There are no Java keywords to declare particular applications of inheritance in Java, they are formed by a combination of extends, implements and other Java programming devices like abstract and final methods, visibility modifiers and so on. Really it is the overall configuration of class, variable and method hierarchies that shapes the inheritance relationships that exist, and classes may serve more than one role.

Q: What is the difference between abstract classes and inheritance?

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 some 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.

Q: How does inheritance avoid duplication?

A: To show how Java inheritance can avoid duplication, consider two classes: Car and Motorcycle which both implement an interface method moveForward(). Here's some example code for the moveForward() method in the Car class.

… full answer hidden

Premium members click below for full answer
How does inheritance avoid duplication?

Q: How do packages affect inheritance in Java?

A: Inheritance is concerned with the properties and behaviour that a class aquires by extending a superclass, and the polymorphic types it acquires by implementing interfaces. The package a class belongs to affects the inheritance patterns it can adopt and may pass down to subclasses through its visibility modifiers, but it is also about assigning a fully qualified class name.

A fully qualified class name like com.example.util.Date distinguishes a non-standard Date class from the Java API class java.util.Date and the java.sql.Date class for example. That means you can use all three Date types in the same class and refer to them specifically without ambiguity.

The package assignment of a class combined with the implicit package visibility, public, protected or private visibility modifiers on the class overall control which other classes can extend it. When those modifiers are applied to a variable or method they affect which can be accessed by other classes and subclasses. So the package assignment combined with visibility modifiers shape the API a class exposes to the Java environment.

Multiple inheritance

Q: Why doesn't Java support multiple inheritance?

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 it creates ambiguity when a class inherits methods from two superclasses with the same method signature: which version should be called?

… full answer hidden

Premium members click below for full answer
Why doesn't Java support multiple inheritance?

Q: Doesn't implicit Object inheritance create multiple inheritance?

A: No, this is a misunderstanding of implicit object inheritance. Every Java class is ultimately descended from the Object superclass, whether there is an extends Object statement or not. If you extend an Application Programming Interface (API) class, the Object inheritance is passed down through that immediate superclass, not from the superclass and the Object class too. Implicit inheritance from the Object class descends through a single line of parent classes to ensure all user defined classes have the standard toString(), equals() and hashCode() methods.

Q: Can you prove that Object is the ultimate superclass in Java?

A: You can prove that the Object class is the superclass of all others by casting any class to an Object. If you have a reference to a class instance in the variable testInstance then cast it to an Object as follows.

Object objectType = null;

try {

  objectType = (Object) testInstance;

  System.out.println("Instance successfully cast to an Object.");
}
catch (ClassCastException cce) {

  // Should never be thrown
  System.err.println("Instance could not be cast to an Object.");
}
    
Q: Is multiple interface inheritance better than extending a class?

A: You should make a judgement about which forms of inheritance are better for a particular Java application. In many cases you should use a mixture of inheritance techniques. The judgement you make will depend on the nature, scale and context of the solution you are developing.

For most relatively simple, small scale applications that can operate independently of other Java systems, class inheritance works well because of its simplicity and re-use of code. Interface inheritance tends to be used in slightly larger, broader applications, but is usually used in combination with class inheritance, not separately.

Some Java programmers argue that class inheritance should be avoided because it creates a rigid coupling and dependency between a class and its superclasses. A class can only have one superclass, so it can be difficult to extract a class from its hierarchy for use elsewhere. A more flexible alternative is to compose a class of one or more internal class fields and fulfil an interface by creating a thin “wrapper” around them.

The example below implements the standard java.util.List and an example Named interface by adapting a String and a Vector, not by inheritance. The String and the Vector are encapsulated by the host class so it is not tightly coupled.

… full answer hidden

Premium members click below for full answer
Is multiple interface inheritance better than extending a class?

Q: Can I achieve multiple inheritance without interfaces?

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.

Q: Can we achieve multiple inheritance with the extends keyword?

A: No, it is not possible to achieve multiple inheritance in Java using the extends keyword alone. A Java class may only extend one superclass. A limited form of multiple inheritance can be created where a class extends a superclass and implements one or more interfaces. The subclass would be type-compatible with the superclass and the interfaces, though it would not inherit any concrete behaviour from the interfaces.

Extending classes

Q: What's the difference between importing and extending a 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.

… full answer hidden

Premium members click below for full answer
What's the difference between importing and extending a class?

Q: Can we explicitly inherit from the Object class?

A: Whenever we declare a new class without an explicit extends keyword, the class implicitly extends the fundamental Object class. When you explicitly extend a different class, that will be descended from the Object class at some point in its hierarchy. It may help to understand the inheritance structure more clearly if you explicitly extend the Object class and it would not be an error to do so.

public class Example1 {

  // Implicitly extends Object
}

public class Example2 extends Object {

  // Explicitly extends Object
}

public class Example3 extends Example1 {

  // Ultimately extends Object
}
      
Q: How can I use inheritance in graphical user interfaces?

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.

Q: How can I prevent a class from being extended?

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
}
      
Q: The private modifier prevents inheritance too!

A: The final keyword is primarily concerned with blocking any subclass override of a method, while the method remains accessible by its subclasses and possibly other classes too. If a method is marked private it is not visible to the subclass, so cannot be overridden, but no other class can call the method either.

If you use the private modifier to prevent overrides it can also lead to confusing cases where the subclass defines a method with the same signature as its superclass. The compiler will not issue a warning in this case.

Overridden methods

Q: What is overriding?

A: So long as a class and its methods are not marked final, a subclass can declare a method with the same signature as one in a superclass 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.";
}
      
Q: Can an overridden method return 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 different 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”.

Q: Why do overridden methods on a subclass have priority over the superclass?

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 Application Programming Interface (API). The technique of overriding effectively says “use this special implementation of the method instead of the superclass version”.

Q: Can you give an example application that shows overriding?

A: The method override example below shows several aspects of inheritance. Both classes implement the ObjectRenderer interface, which has one method, void render(Object). The superclass BasicObjectRenderer has a default constructor and uses the System.out PrintStream to render the object, the subclass HTMLObjectRenderer has a constructor that takes an OutputStream argument to render the object with HTML formatting.

… full answer hidden

Premium members click below for full answer
Can you give an example application that shows overriding?

Q: How do you prevent a method from being overridden?

A: To prevent a specific method from being overridden in a subclass, use the final modifier on the method declaration, which means “this is the final implementation of this method”, the end of its inheritance hierarchy.

public final void exampleMethod() {

  // Method statements
}
      
Q: How can I find the inherited attributes of a class?

A: It is possible to deduce the inherited fields and methods of a Java class using reflection through a recursive process that uses the Class method getSuperclass(). The Class method getFields() returns an array of Field objects for public fields only. The getDeclaredFields() returns an array of all declared fields in the current class, including private fields, but not the inherited fields. The getMethods() and getDeclaredMethods() methods return equivalent arrays of Method objects.

To obtain a list of all inherited fields or methods, a program would need to get the superclass of the object in question, store the return value for its getDeclaredFields() method then process each of its superclasses in turn. The simple example below prints out all the inherited fields in its immediate superclass Thread.

… full answer hidden

Premium members click below for full answer
How can I find the inherited attributes of a class?

Techniques for overridden superclasses

Q: How can I call an overridden method in the superclass?

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();
      
Q: Can you give an example call to an overridden superclass method?

A: The example below shows a general class GeneralNotifier with a method printMessage() which is overridden in the subclass SpecialNotifier. The SpecialNotifier also has a method printParentMessage() that calls the superclass version of printMessage().

… full answer hidden

Premium members click below for full answer
Can you give an example call to an overridden superclass method?

Q: How can I get the superclass to call back to a method in the subclass?

A: This type of call to a method in the superclass chained to a call in the subclass can be done if the superclass calls an abstract method that is overridden in the subclass, see the example below.

… full answer hidden

Premium members click below for full answer
How can I get the superclass to call back to a method in the subclass?

Q: A superclass can call an overriden method in a subclass too!

A: Yes, you can also have a superclass call custom methods in a subclass when the subclass overrides a concrete method. However, in this case, there is no “contract” between the superclass and the subclass, no guarantee that the subclass actually does override the superclass implementation. The implied override approach may work if a single programmer writes the superclass and all subclasses, but cannot ensure that another programmer would complete the design pattern.

The advantage of the abstract method approach is that subclass programmers must discover the intended purpose of the method and write an appropriate implementation. This requires extra effort and puts a greater responsibility on the implementor, but should enforce the contract established by the superclass.

Home · Web fonts · Font stacks · FAQs · Java · CSS · Javascript · HTML · Site manager