Java Reference
In-Depth Information
public class A {
public final void m1() {
// Code goes here
}
public void m2() {
// Code goes here
}
}
public class B extends A {
// Cannot override A.m1() here because it is final in class A
// OK to override m2() because it is not final in class A
public void m2() {
// Code goes here
}
}
You will find many classes and methods in the Java class libraries that are declared final . Most notably, the
String class is final . Why would you declare a class or a method as final ? In other words, why would you want
to prevent subclassing of a class or overriding/hiding of a method? The main reasons for doing this are security,
correctness, and performance. If your class is important for security reasons, you do not want someone to inherit
from your class and mess with the security that your class is supposed to implement. Sometimes, you declare a
class/method final to preserve the correctness of the program. A final method may result in better performance at
runtime because a code optimizer is free to inline the final method calls.
Abstract Classes and Methods
Sometimes you may create a class just to represent a concept rather than to represent objects. Suppose you want to
develop classes to represent different shapes. A shape is just an idea or a concept. It does not exist in reality. Suppose
someone asks you to draw a shape. Your immediate response would be, “What shape do you want me to draw?” If
someone asks you to draw a circle or a rectangle, it makes sense to you. Java lets you create a class whose objects
cannot be created. Its purpose is just to represent an idea, which is common to objects of other classes. Such a class is
called an abstract class. The term “concrete class” is used to denote a class that is not abstract and whose objects can
be created. So far, all your classes have been concrete classes.
You need to use the abstract keyword in the class declaration to declare an abstract class. For example, the
following code declares a Shape class abstract :
public abstract class Shape {
// No code for now
}
Because the Shape class has been declared abstract , you cannot create its object even though it has a public
constructor (the default one added by the compiler). You can declare a variable of an abstract class as you do for a
concrete class. The following code snippet shows some valid and invalid uses of Shape class:
Shape s; // OK
new Shape(); // An error. Cannot create a Shape object
 
Search WWH ::




Custom Search