0% found this document useful (0 votes)
11 views

Inheritance Google

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Inheritance Google

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Java

Chapter 8: Inheritance

Slides material compiled from


Java - The Complete Reference 9th Edition
By
Herbert Schildt
Inheritance Basics
• Cornerstone feature of object-oriented
programming
– Allows creation of hierarchical classifications
– Superclass: class that is inherited
– Subclass: class that does the inheriting
• Subclass inherits all members defined by
superclass and adds its own elements
• How? Use the extends keyword

Note: Java does not support the inheritance of multiple superclasses into a
single subclass

Rakhi Saxena (Internet Technologies) 2


A simple example of inheritance
// Create a superclass.
class A {
int i, j;
void showij() {
System.out.println("i and j: " + i + " " + j);
}
}

// Create a subclass by extending class A.


class B extends A {
int k;
void showk() {
System.out.println("k: " + k);
}
void sum() {
System.out.println("i+j+k: " + (i+j+k));
}
}

Rakhi Saxena (Internet Technologies) 3


Example (contd)
class SimpleInheritance {
public static void main(String args []) {
A superOb = new A();
B subOb = new B();
superOb.i = 10; // The superclass may be used by itself.
superOb.j = 20;
System.out.println("Contents of superOb: ");
superOb.showij();
System.out.println();
subOb.i = 7; subOb.j = 8; subOb.k = 9;
System.out.println("Contents of subOb: ");
subOb.showij();
subOb.showk();
System.out.println();
System.out.println("Sum of i, j and k in subOb:");
subOb.sum();
}
}
Rakhi Saxena (Internet Technologies) 4
Example (contd)
class SimpleInheritance {
public static void main(String args []) {
A superOb = new A();
B subOb = new B();
superOb.i = 10; // The superclass may be used by itself.
superOb.j = 20;
System.out.println("Contents of superOb: ");
superOb.showij();
System.out.println();
subOb.i = 7; subOb.j = 8; subOb.k = 9; OUTPUT
System.out.println("Contents of subOb: "); Contents of superOb:
subOb.showij(); i and j: 10 20
subOb.showk(); Contents of subOb:
System.out.println(); i and j: 7 8
System.out.println("Sum of i,j and k in subOb:"); k: 9
subOb.sum(); Sum of i, j and k in subOb:
}
i+j+k: 24
}

Rakhi Saxena (Internet Technologies) 5


Member Access and Inheritance
• Subclass cannot access private members of
the superclass
• Major advantage of inheritance is that once
you have created a superclass that defines the
attributes common to a set of objects, it can
be used to create any number of more specific
subclasses.
• Each subclass can precisely tailor its own
classification

Rakhi Saxena (Internet Technologies) 6


A Superclass Variable Can Reference a
Subclass Object
• Reference variable of a superclass can be assigned a reference to
any subclass derived from that superclass
class RefDemo {
public static void main(String args[]) {
BoxWeight weightbox = new BoxWeight(3, 5, 7, 8.37);
Box plainbox = new Box();
double vol;
vol = weightbox.volume();
System.out.println("Volume of weightbox is " + vol);
System.out.println("Weight of weightbox is " + weightbox.weight);
System.out.println();
plainbox = weightbox;
vol = plainbox.volume(); // OK, volume() defined in Box
System.out.println("Volume of plainbox is " + vol);
/* The following statement is invalid because plainbox
does not define a weight member. */
// System.out.println("Weight of plainbox is " + plainbox.weight);
}
}
Rakhi Saxena (Internet Technologies) 7
Access restrictions of superclass
variable
• Type of the reference variable—not the type
of the object that it refers to—that determines
what members can be accessed
• When a reference to a subclass object is
assigned to a superclass reference variable, it
will have access only to those parts of the
object defined by the superclass

Rakhi Saxena (Internet Technologies) 8


Using super
• Whenever a subclass needs to refer to its
immediate superclass, it can do so by use of
the keyword super
• super has two general forms
– The first calls the superclass’ constructor
– The second is used to access a member of the
superclass that has been hidden by a member of a
subclass

Rakhi Saxena (Internet Technologies) 9


Using super to Call Superclass
Constructors
class BoxWeight extends Box {
double weight; // weight of box
// initialize variables using super()
BoxWeight(double w, double h, double d, double m) {
super(w, h, d); // call superclass constructor
weight = m;
}
}

• When a subclass calls super( ), it is calling the constructor


of its immediate superclass
• super( ) must always be the first statement executed
inside a subclass constructor
Rakhi Saxena (Internet Technologies) 10
Using super to overcome name hiding
class A {
int i;
}
class B extends A {
int i; // this i hides the i in A
B(int a, int b) {
super.i = a; // i in A
i = b; // i in B
}
void show() {
System.out.println("i in superclass: " + super.i);
System.out.println("i in subclass: " + i);
}
}

class UseSuper {
public static void main(String args[]) {
B subOb = new B(1, 2);
subOb.show();
}
}

NOTE: instance variable i in B hides the i in A, super allows access to the I defined in the superclass

Rakhi Saxena (Internet Technologies) 11


Creating a Multilevel Hierarchy
class Box {
private double width, height, depth;

Box(Box ob) { // pass object to constructor


width = ob.width; height = ob.height; depth =
ob.depth;
}
Box(double w, double h, double d) {
width = w; height = h; depth = d;
}
Box() {
width = -1; height = -1; depth = -1;
}
Box(double len) {
width = height = depth = len;
}
double volume(){
return width * height * depth;
} Rakhi Saxena (Internet Technologies) 12
}
Creating a Multilevel Hierarchy (contd)
class BoxWeight extends Box {
double weight; // weight of box
BoxWeight(BoxWeight ob) { // pass object to
constructor
super(ob); weight = ob.weight;
}
BoxWeight(double w, double h, double d, double m) {
super(w, h, d); // call superclass constructor
weight = m;
}
BoxWeight() {
super(); weight = -1;
}
BoxWeight(double len, double m) {
super(len); weight = m;
}
}

Rakhi Saxena (Internet Technologies) 13


Creating a Multilevel Hierarchy (contd)
class Shipment extends BoxWeight {
double cost;
Shipment(Shipment ob) { // pass object to constructor
super(ob); cost = ob.cost;
}
Shipment(double w, double h, double d, double m,
double c) {
super(w, h, d, m); cost = c;
}
Shipment() {
super(); cost = -1;
}
Shipment(double len, double m, double c) {
super(len, m); cost = c;
}
} Rakhi Saxena (Internet Technologies) 14
Creating a Multilevel Hierarchy (contd)
class DemoShipment {
public static void main(String args[]) {
Shipment sh1 = new Shipment(10, 20, 15, 10, 3.41);
Shipment sh2 = new Shipment(2, 3, 4, 0.76, 1.28);
double vol = sh1.volume();
System.out.println("Volume of sh1 is " + vol);
System.out.println("Weight of sh1 is "+ sh1.weight);
System.out.println("Shipping cost: $" + sh1.cost);
System.out.println();
vol = sh2.volume();
System.out.println("Volume of sh2 is " + vol);
System.out.println("Weight of sh2 is "+ sh2.weight);
System.out.println("Shipping cost: $" + sh2.cost);
}
}
Rakhi Saxena (Internet Technologies) 15
Creating a Multilevel Hierarchy (contd)

OUTPUT
Volume of shipment1 is 3000.0
Weight of shipment1 is 10.0
Shipping cost: $3.41
Volume of shipment2 is 24.0
Weight of shipment2 is 0.76
Shipping cost: $1.28

Rakhi Saxena (Internet Technologies) 16


When Constructors Are Executed
• In a class hierarchy, constructors complete
their execution in order of derivation, from
superclass to subclass
• This order is the same whether or not super( )
is used
– If super( ) is not used, then the default or
parameterless constructor of each superclass will
be executed

Rakhi Saxena (Internet Technologies) 17


Method Overriding
• In a class hierarchy, when a method in a subclass has
the same name and type signature as a method in its
superclass, subclass method overrides superclass
method
• When an overridden method is called from within its
subclass, it always refers to the version of that method
defined by the subclass
• Method overriding occurs only when the names and
the type signatures of the two methods are identical
– If they are not, then the two methods are simply
overloaded

Rakhi Saxena (Internet Technologies) 18


Method Overriding Example
class A { class C extends B {
int i, j; C() {
A(int a, int b) {
System.out.println("Insid
i = a;j = b;
e C's constructor.");
}
void show() { }
System.out.println("i and j: }
" + i + " " + j); class CallingCons {
}
}
public static void
class B extends A {
main(String args[]) {
B() { C c = new C();
System.out.println("Inside }
B's constructor."); }
}
}
OUTPUT
Inside A's constructor
Inside B's constructor
Inside C's constructor
Rakhi Saxena (Internet Technologies) 19
Dynamic Method Dispatch
• Mechanism by which a call to an overridden
method is resolved at run time, rather than
compile time (run-time polymorphism)
– When an overridden method is called through a
superclass reference, Java determines which version
of that method to execute based upon the type of the
object being referred to at the time the call occurs
– If a superclass contains a method that is overridden by
a subclass, then when different types of objects are
referred to through a superclass reference variable,
different versions of the method are executed

Rakhi Saxena (Internet Technologies) 20


Dynamic Method Dispatch (Example)
class A {
void callme() {
{ System.out.println("Inside A's callme method");
}
}
class B extends A {
void callme() // override callme()
{ System.out.println("Inside B's callme method"); }
}
class C extends A {
void callme() {// override callme()
{ System.out.println("Inside C's callme method");}
}
}

Rakhi Saxena (Internet Technologies) 21


Dynamic Method Dispatch (Example
contd)
class Dispatch {
public static void main(String args[]) {
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C
A r; // obtain a reference of type A
r = a; // r refers to an A object
r.callme(); // calls A's version of callme
r = b; // r refers to a B object
r.callme(); // calls B's version of callme
r = c; // r refers to a C object
r.callme(); // calls C's version of callme
} OUTPUT
} Inside A's callme method
Inside B's callme method
Inside C's callme method
Rakhi Saxena (Internet Technologies) 22
Why Overridden Methods?
• Overridden methods allow Java to support run-time
polymorphism
• Polymorphism allows a general class to specify
methods that will be common to all of its derivatives,
while allowing subclasses to define the specific
implementation of some or all of those methods
• “one interface, multiple methods”
• Hierarchy moves from lesser to greater specialization
• Enables existing code libraries to call methods on
instances of new classes without recompiling while
maintaining a clean abstract interface
Rakhi Saxena (Internet Technologies) 23
Using final with Inheritance
• keyword final has three uses
– Can be used to create the equivalent of a named
constant
– Can be used to prevent overriding
– Can be used to prevent inheritance

Rakhi Saxena (Internet Technologies) 24


Using final to Prevent Overriding
• To disallow a method from being overridden, specify
final as a modifier at the start of its declaration
class A {
final void meth() {
System.out.println("This is a final method.");
}
}
class B extends A {
void meth() { // ERROR! Can't override
System.out.println("Illegal!");
}
}
• Final methods can provide a performance enhancement:
Compiler is free to inline calls to them because it “knows”
they will not be overridden by a subclass

Rakhi Saxena (Internet Technologies) 25


Using final to Prevent Inheritance
• Declaring a class as final implicitly declares all of
its methods as final
– it is illegal to declare a class as both abstract and final
since an abstract class is incomplete by itself and
relies upon its subclasses to provide complete
implementations
final class A {
//...
}
// The following class is illegal.
class B extends A { // ERROR! Can't subclass A
//...
}
Rakhi Saxena (Internet Technologies) 26
The Object Class
• All classes in Java are subclasses of Object class
– Implies that reference variable of type Object can
refer to an object of any other class/ and any array
• Methods defined by Object class are available in
every object
– Any class may override the non-final methods of
Object class
– equals( ) method compares two objects
– toString( ) method returns a string that contains a
description of the object on which it is called
• automatically called when an object is output using println( )

Rakhi Saxena (Internet Technologies) 27


Methods defined by Object class

Rakhi Saxena (Internet Technologies) 28

You might also like