Java Reference
In-Depth Information
Does the following
HouseCat
class compile?
1. public class HouseCat extends Feline {
2. public void eat() {
3. System.out.println(“HouseCat is eating”);
4. }
5.
6. public void breathe() {
7. System.out.println(“HouseCat is breathing”);
8. }
9. }
Because
HouseCat
extends from
Feline
and
Feline
inherits the abstract
walk
method
from
Mammal
,
HouseCat
must either override
walk
or declare itself
abstract
. Because it does
neither, the class does not compile and generates the following error:
HouseCat.java:1: HouseCat is not abstract and does not override
abstract method walk() in Mammal
public class HouseCat extends Feline {
^
Declaring Interfaces
An
interface
is a collection of abstract methods. A class implements an interface, inheriting
all the abstract methods declared in the interface. Therefore, a class that implements an
interface must either override the interface methods or the class must be declared
abstract
.
An interface has the following properties:
An interface is defined in a
.java
file. If the interface is
public
, the name of the file
must match the name of the class. If the interface has the default access, it is only
accessible from within its package.
The bytecode file for a compiled interface is a
.class
file that matches the name of the
interface. All the rules of package names and subdirectories that apply to classes also
apply to interfaces.
All the methods in an interface are abstract, whether or not the
abstract
keyword is
explicitly denoted.
All the methods in an interface are public, whether or not they are explicitly declared
public
.
The fields of an interface are
public
,
static
, and
final
.
An interface cannot declare static methods.
An interface has some similarities to a class, but an interface is not a class. For example,
an interface cannot be instantiated, and it cannot contain any instance fi elds.
Search WWH ::
Custom Search