CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ | Grades

Inheritance

Inheritance
Abstract and final keywords
final keyword

How to work with the final keyword

  • To prevent a class from being inherited, you can create a final class.
  • To prevent subclasses from overriding a method of a superclass, you can create a final method.
  • To prevent a method from assigning a new value to a parameter, you can create a final parameter.
  • All methods in a final class are automatically final methods.
  • Coding the final keyword for classes and methods can result in a minor performance improvement because the compiler doesn't have to allow for inheritance and polymorphism.

A final class

public final class Book extends Product
{
    // all methods in the class are automatically final
}

A final method

public final String getVersion()
{
    return version;
}

A final parameter

public void setVersion(final String version)
{
    // version = "new value"; // not allowed
    this.version = version;
}
Previous | abstract keyword | final keyword