Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^366) | Inheritance, Polymorphism, and Scope


Summary


Object-oriented languages such as Java organize class data types into a hierarchy. At
the top of Java’s hierarchy is a class called Objectthat provides a few basic
operations. Using inheritance, other classes extend Objectand are said to be derived
from it. Derived classes inherit all of the publicand protectedfields and methods of
their superclass, except for its constructors. We must explore the entire inheritance
hierarchy for a class to determine its full interface.
Instance methods can override superclass instance methods, and class methods
and fields can hide superclass class methods and fields. Overriding and hiding
enable us to change the meaning of a method or field when extending a superclass
with a derived class. In this way, the derived class can retain the same form of inter-
face, but operate in a different manner.
Constructors are not inherited by derived classes. The first statement in a
constructor must be a call to a constructor for the superclass. Otherwise, Java will
automatically insert such a call to the default constructor for the superclass.
Java allows us to declare multiple methods with the same name as long as they
have different signatures. The method name is then said to be overloaded. The
signature consists of the method name plus the types of its parameters in a particu-
lar order. The return type and modifiers are not part of the signature. Java
determines which version of an overloaded method to call by examining the types in
the argument list and selecting the method with the matching parameter list.
Sometimes we need to access a method or field in a superclass that has been
overridden or hidden. We can use the superkeyword to refer to the superclass
version of a field or method instead of the local version. Similarly, a method can de-
fine a local variable or parameter with the same name as a field in the class; we can
then use thisto refer to the instance version instead of the local version.
Scope rules determine the range of code that has access to an identifier. Internal
scope rules specify where class members can be accessed within a class. In Java,
members can be used anywhere within a class, with two exceptions: Class variables

13.For instances of a class to be written on a file, the class must implement the
Serializableinterface.
14.When an instance of a class is read from a file, the object must be type cast
back into its original class. For this reason, the mainmethod of an application
that uses the method readObjectmust include ClassNotFoundExceptionin its
throwsclause.
Free download pdf