Class 1, Part 2 |
Intro to Java 30-IT-396 |
|
Final Classes and Methods
-
What if you don't want your class to be subclassed?
-
You can prevent it by adding the final keyword to the class definition.
-
In other words, what used to be
is now
public final class Thing { .
-
You cannot subclass this. If you try to extend this class, the compiler
will give you an error.
-
You can do this with methods, too. You can prevent methods from being
extended by adding a final keyword.
public void changeSalary() {
is now
public final void chagneSalary() {
-
Now, you can subclass the class that contains these methods, but you cannot
override these methods.
-
Note, all methods in a final class are automatically final. After
all, if you can't subclass (extend) the class, how are you going to override
the method?
-
Declaring a class final does not affect the fields, however.
-
Why would you want to do this?
-
In general, final classes and methods are more efficient because they use
static binding, not dynamic binding.
-
You have better control over your class. Imagine if you are a vendor
that sells Java classes. There might be some methods that you want
to protect, especially methods that gather volume data!
Casting



Created by: Brandan
Jones January 4, 2002