You are on page 1of 36

Inheritance

1
Inheritance
 A class declaration may include the extends clause,
which is used to indicate the class which the declared
class extends (or is derived, or inherits from).

Example:
// filename: ClassOne.java
public class ClassOne {
}

// filename: ClassTwo.java
public class ClassTwo extends ClassOne {
}
2
Inheritance
 In the example, ClassOne is called the superclass (a.k.a.
supertype or base class), while ClassTwo is called the
subclass (a.k.a. subtype or derived class).
 A class may inherit only from one superclass, but may, in
turn, have any number of subclasses.

3
Inheritance
 Several levels of inheritance relationships may be defined
(i.e., a class may be the superclass of another class, which
may in turn be the superclass of yet another class, and so
on). The sequence of classes involved in superclass-
subclass relationships is called the inheritance chain.
 The familiar terms ancestor and descendant classes are
typically used to refer to classes in the inheritance chain
(depending on their relationship to the other classes in
the chain).

4
Inheritance
 The predefined class Object (defined in the java.lang
package) is a special class since it is the only class that
does not inherit from another class.
 Any class that does not explicitly specify its superclass
through an extends declaration implicitly extends the
predefined Object class; thus, the declaration
class A {}
is equivalent to the declaration
class A extends Object {}

5
Inheritance
 The set of all classes and their relationships (i.e., the set
of all inheritance chains taken collectively) forms the
inheritance hierarchy, which can be visualized as a tree
structure, with the class Object as its root.
 Inheritance provides for two main purposes: state and/or
behavior sharing, and substitutability.

6
Inheritance
 A derived class inherits the state and behavior associated
with its base class, and may be provided with additional
characteristics of its own. It may also override (i.e.,
modify) the behaviors that it inherits from its base class.
Depending on the accessibility of the features of the
superclass, some features inherited by a subclass may not
be accessible from within the subclass itself.

7
Inheritance
Example:
// filename: Features.java
public class Features {
// this will be inherited by subclasses of Features,
// but will not be accessible to those subclasses…
private int i;
// this will be accessible to subclasses…
protected char c;
public boolean b; // as is this…
}

8
Inheritance
 Instance methods may be inherited “as is” from superclasses,
but subclasses may also provide their own implementations
of inherited instance methods (i.e., subclasses may
“override” a method that is inherited from a superclass).
Overridden methods must be provided with access
modifiers that is either as, or less restrictive than, the
methods defined in the superclass, but cannot be made
more restrictive in the subclass. Also, the overriding
method must have exactly the same method header (i.e., same
return type, name, and number and types of parameters) as
the method which is being overridden (otherwise, the
method will be overloaded across classes).

9
Inheritance
Examples:
// filename: SuperOverride.java
public class SuperOverride {
public void methodOne() {
System.out.println(”methodOne from superclass…”);
}
protected void methodTwo() {
System.out.println(”methodTwo from superclass…”);
}
public void methodThree() {
System.out.println(”methodThree from superclass…”);
}
}
10
Inheritance
Examples:
// filename: SubOverride.java
public class SubOverride extends SuperOverride {
// this overrides methodTwo() of the superclass…
// note that this is less restrictive (public
// here visàvis protected in the superclass)…
public void methodTwo() {
System.out.println(”methodTwo from subclass…”);
}

// this will be invalid, since the accessibility of the overriding method is


// more restrictive (i.e., from public to private)…
// private void methodOne() {}

public void methodThree(int i){ // this method is overloaded across classes…


System.out.println(”methodThree from subclass…”);
}
}

11
Inheritance
Examples:
// filename: TestOverride.java
public class TestOverride {
public static void main(String[] args) {
SubOverride sb = new SubOverride();
sb.methodOne(); // calls superclass methodOne()…
sb.methodTwo(); // calls subclass methodTwo()…
sb.methodThree(); // calls superclass methodThree()…
sb.methodThree(1); // calls subclass methodThree()…
}
}

12
Inheritance
 Static methods cannot be overridden. Instance methods
cannot be overridden by static methods.
 Constructors, unlike methods, are not inherited by
subclasses, and cannot be overridden. They can be
overloaded, but only within the scope of the class where
they are declared.

13
Inheritance
 When subclasses inherit instance fields from their
superclasses, the instantiation of the state of the subclass
object which was inherited from the superclass is still
considered a responsibility of the constructor for the
superclass. During a subclass instantiation, a call to the
superclass constructor must be performed to properly
initialize the state of the subclass which consists of the
instance fields inherited from the superclass.

14
Inheritance
 The super keyword is used in a subclass constructor to
explicitly control the superclass constructor that must be
invoked before the execution of the subclass constructor
proceeds. If provided, it must be the first statement in a
subclass constructor. If omitted, it is implicitly assumed
that a call to the default superclass constructor is
performed before the subclass constructor proceeds (if in
case the superclass has no default constructor, and no
explicit call to super is done, the instantiation of the
subclass object will fail).

15
Inheritance
Example:
// filename: ConsInherit.java
public class ConsInherit {
private int i = 0;
private boolean b = false;

public ConsInherit (int i) {


this.i = i;
}

public ConsInherit(boolean b) {
this.b = b;
}
}
16
Inheritance
Example:
// filename: SubInherit.java
public class SubInherit extends ConsInherit {
public SubInherit (int i) { // this calls the first constructor
super(i); // defined for ConsInherit…
// other constructor code here…
}
public SubInherit (boolean b) { // this calls the second constructor
super(b); // defined for ConsInherit…
// other constructor code here…
}
public SubInherit() { // this will not work since it will
} // implicitly invoke the default
// constructor for ConsInherit, which
// happens to be undefined…
}

17
Inheritance
 An object reference to a subclass can be assigned to a
superclass variable, but not viceversa (i.e., a subclass
reference may be “substituted” for a superclass reference,
but not the other way around). A class type cast can be
used to force a subclass reference that was assigned to a
superclass variable to be converted back into an object
reference of the subclass type (class type casts, however,
cannot be used to force an object reference to be
converted into another object reference of a class type
which is not the original type, or a subclass, of the object
reference being typecasted).

18
Inheritance
Example:
// filename: TestAssign.java (using classes SuperOverride and SubOverride)
public class TestAssign {
public static void main (String[] args) {
SuperOverride sp;
SubOverride sb;
sp = new SubOverride(); // this is allowed…
sb = new SuperOverride(); // but not this, so comment it out…
Object o = new SuperOverride(); // this works, since Object is a
// superclass of all other classes…
sp = o; // this won’t work, so comment it out…
sp = (SuperOverride) o; // but this will…
sb = (SubOverride) o; // this will compile, but will cause
} // a runtime error when executed…
} // (try to determine why)…

19
Inheritance
 In the face of substitutability, invocation of overridden
methods makes use of dynamic binding, in which the
method version that is executed is determined at runtime
based on the actual type of the current object reference
held by the object variable when the method is invoked.

20
Inheritance
Example:
// filename: TestMethod.java (using classes SuperOverride and SubOverride)
public class SubInherit extends ConsInherit {
public static void main (String[] args) {
SuperOverride sp;
sp = new SuperOverride();
sp.methodTwo(); // calls superclass methodTwo()…
sp = new SubOverride();
sp.methodTwo(); // calls subclass methodTwo()… note that the
} // same object variable (sp) is used in both
} // calls, with different results…

21
Inheritance
 The instanceof operator can be used to determine
whether or not the current object reference held by an
object variable is of a particular class type.
Example:
// filename: TestInstanceOf.java (using classes SuperOverride and SubOverride)
import java.io.*;
public class TestInstanceOf {
public static String instanceName(Object o) {
if (o instanceof SubOverride)
return ”Sub”;
else if (o instanceof SuperOverride)
return ”Super”;
else
return ”Something Else”;
}

22
Inheritance
Example:
// filename: TestInstanceOf.java (continuted…)

public static void main(String[] args) {


Object o = new SuperOverride();
System.out.println(instanceName(o)); // prints ”Super”…

o = new SubOverride();
System.out.println(instanceName(o)); // prints ”Sub”…

o = new Object();
System.out.println(instanceName(o)); // prints ”Something Else”…
}
}

23
Packages

24
Packages
 Packages provide a mechanism for grouping a set of
logically related classes into a single named unit. They
are also used to provide a scoping unit (i.e., control the
visibility of class and/or class member declarations) above
that of the scope provided by a class declaration (class
scope).
 Classes in a package typically provide services or features
that are related to one another (e.g., math operations, I/O
mechanisms, networking, etc.).
 Classes in a package can then be used (or imported) into
other classes (or packages) that need access to the
services provided by the classes in the package.
25
Packages
 Class declarations can indicate in which package the class
will belong to. In the given example, the class ClassOne
is declared to belong to the package named PackOne via
the package statement, which, if provided, must appear
before any other statement in a source file. Any class can
belong to only one package, so there must be only one
package statement in a class declaration.
Example:
// filename: ClassOne.java
package PackOne;
public class ClassOne {
}

26
Packages
 It is possible to have a hierarchy of packages (i.e., a “sub-
package” may exist within a package, up to multiple
“levels”), and classes may be placed anywhere within such
a hierarchy. In the next example, a “subpackage”
SubPackOne is defined under the PackOne package, and
the class ClassTwo is then declared to belong to
SubPackOne.
Example:
// filename: ClassTwo.java
package PackOne.SubPackOne;
public class ClassTwo {
}

27
Packages
 Classes that are declared with no package statement are
considered to belong to an unnamed default package. The
compiled class files for these classes are placed in the
current working directory (usually the same location
where the source files are placed).

28
Packages
 Class declarations may specify which classes they need to
reference through an import statement. The import
statement may specify individual classes in a package, or
the set of all classes within the package. Class
declarations may have zero or more import statements
provided (depending on the other classes which they
reference). Without the appropriate import statements
provided, a class in one package cannot use or reference
classes declared in a different package, unless the class
name itself is qualified with the name of the package that
contains it (e.g., java.lang.String).

29
Packages
Example:
// one or more of the following statements may be placed in a class
// source file…

import PackOne.ClassOne; // refer to ClassOne directly…


import PackOne.*; // refer to all classes in PackOne…
import PackOne.SubPackOne.ClassTwo; // refer to ClassTwo directly…
import PackOne.SubPackOne.*; // refer to all classes in SubPackOne…

30
Packages
 Package names are mapped by the Java compiler to physical
directory names in the local file system. Each directory will
contain the .class files for all the classes in a given package.
These directories are resolved relative to either the current
working directory (where the default package is assumed to
be placed), or to a series of fixed points in the local file system
stored in an environment variable called CLASSPATH. When
compiling a class declared to belong to a package, the Java
compiler places the generated .class file into the appropriate
directory. Similarly, when references to classes are made in a
class declaration, the compiler looks for the .class files for
those classes in the directories indicated in import
statements in the current class.

31
Packages
 For example, assuming that the value of CLASSPATH is
C:\MyClasses, and that the current working directory (where
the source files for ClassOne and ClassTwo in the examples
above are placed) is C:\Work, the compiled .class files for
ClassOne and ClassTwo will be placed, respectively, in
C:\Work\PackOne and C:\Work\PackOne\SubPackOne.

32
Packages
 When another class provides import statements to reference
ClassOne and ClassTwo (such as those provided in the
example above), the Java compiler will look for the compiled
classes in the following directories:
C:\Work\PackOne // for ClassOne…
C:\Work\PackOne\SubPackOne // for ClassTwo…
C:\MyClasses\PackOne // for ClassOne…
C:\MyClasses\PackOne\SubPackOne // for ClassTwo…
 The source files (.java) are typically placed in the same
directory as the .class files, and Java will automatically
compile .java files in case no .class files are found in the
appropriate locations.
33
Packages
 Java also provides a mechanism for archiving a package (along
with the package classes and any and all subpackages and their
classes) into a Java archive file (file name extension: .jar), using
the utility jar.exe. The location of this archive file can then
be specified in the class path to enable the Java compiler to
search the archive for needed class files. The classes in the Java
API class library are typically included in a Java installation in
this archived format.

34
Packages
 If a class declaration accesses another class defined in a
separate package as the current class, the referenced class
must have been declared public in its package. Nonpublic
classes are considered local to their package, and can only be
referenced by classes declared in the same package.
 Classes requiring access to other classes that are defined
within the same package need not provide import statements
for the referenced classes (since they are in the same package
and are therefore automatically in scope of the current class
declaration). It is still good practice to explicitly indicate such
import statements in the class declaration though.

35
Packages
 Class members that are declared with the access modifier
protected are accessible from subclasses of the declaring
class, as well as from classes within the same package as the
declaring class. Class members with default accessibility (i.e.,
those declared with no access modifier) are accessible within
classes that are defined in the same package as the declaring
class (but not in the subclasses of the declaring class which are
located in a different package).
 The class library package java.lang is implicitly imported into
each class source file and thus need not be specified in an
import statement (although it can still be explicitly done so).

36

You might also like