Extending a Class
Purpose:
- To create a class which inherits from another class
Mechanics:
<modifiers> class <class name> extends <superclass name> {/* Instance variables declared and methods defined here. */
}
Example:
public class Circle extends Shape {/* Instance variables declared and methods defined here. */
}
Usage:
- <modifiers> is an optional space-separated list of valid class modifiers.
- <class name> must be a valid identifier unique to the package.
- <class name> will inherit all
non-
privatemethods and instance variables defined in <superclass name>. Thus the methods and instance variables defined for <class name> need be only those things needed to specialize the class. - <superclass name> may also inherit methods and instance variables; if so, <class name> inherits everything that <superclass name> inherits.
Restrictions:
- If <class name> is in a different package than
<superclass name>, then although <class
name> will inherit all
protectedmethods and instance variables from <superclass name>, methods of <class name> will not be able to directly access thoseprotectedmethods and instance variables of other instances through references of type <superclass name>, or through references to other subclasses of <superclass name> outside the package. - A class that implements interfaces can also inherit from a
superclass. The superclass must be extended before the interfaces
are implemented:
<modifiers> class <class name> extends <superclass name> implements <interface list> {/* Instance variables declared and methods defined */
}- public class myClass extends superClass implements myInterface
{
- /* Instance variables declared and methods defined */
}
email suggestions to: cs015tas@cs.brown.edu
