Java Reference
In-Depth Information
Note that if any method is declared abstract, the class must be declared abstract as
well or the compiler will give an error message. The compiler will not permit an
abstract class to be instantiated. An abstract class need not include only abstract
methods. It can also include concrete methods as well, in case there is common
behavior that should apply to all subclasses. In fact, a class marked abstract is
not required to include any abstract methods. In that case, the abstract modifier
simply prevents the class from being instantiated on its own. Abstract classes,
unlike interfaces (see next section), can also declare instance variables. As an
example, our abstract Shape class might declare an instance variable name :
public abstract class Shape {
String name;
abstract double getArea ();
String getName () {
return name;
}
}
Here each subclass inherits the name instance variable. Each subclass also inherits
the concrete method getName() that returns the value of the name instance
variable.
When an abstract class does declare an abstract method, then that method
must be made concrete in some subclass. For example, let's suppose that class A
is abstract and defines method doSomething() . Then class B extends A but
does not provide a doSomething() method:
abstract class A {
abstract void doSomething ();
}
class B extends A {
// Fails to provide a concrete implementation
// of doSomething ()
void doSomethingElse () {...}
}
In this case, the compiler complains as follows:
Bisnot abstract and does not override abstract method
doSomething() in A class B extends A {
This message indicates that not overriding doSomething() in class B is okay if
B is declared to be abstract too. In fact, that is true. If we don't want B to provide
doSomething() , then we can declare B abstract as well:
Search WWH ::




Custom Search