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

Chapter 8 Inheritance

Uploaded by

Al Shahrear Emon
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Chapter 8 Inheritance

Uploaded by

Al Shahrear Emon
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 36

Chapter 8: Inheritance

Dr. Mohammad Rashedur Rahman


Hierarchical Abstraction
• An essential element of object-oriented programming is abstraction.
• Humans manage complexity through abstraction. For example, people do not think of a
car as a set of tens of thousands of individual parts. They think of it as a well-defined
object with its own unique behavior.
• This abstraction allows people to use a car without being overwhelmed by the
complexity of the parts that form the car. They can ignore the details of how the engine,
transmission, and braking systems work.
• Instead they are free to utilize the object as a whole.
Class Hierarchy
A child class of one parent can be the parent of another child, forming class hierarchies

Animal

Reptile Bird Mammal

Snake Lizard Parrot Horse Bat

 At the top of the hierarchy there’s a default class called


Object.
Class Hierarchy
• Good class design puts all common features as high in the hierarchy as
reasonable
• The class hierarchy determines how methods are executed
• inheritance is transitive
• An instance of class Parrot is also an instance of Bird, an instance
of Animal, …, and an instance of class Object
Base Class Object

• In Java, all classes use inheritance.


• If no parent class is specified explicitly, the base class Object is implicitly
inherited.
• All classes defined in Java, is a child of Object class, which provides minimal
functionality guaranteed to e common to all objects.
Base Class Object (cont)
Methods defined in Object class are;
1.equals(Object obj) Determine whether the argument object is the same as
the receiver.
2.getClass() Returns the class of the receiver, an object of type Class.
3.hashCode() Returns a hash value for this object. Should be overridden when the
equals method is changed.
4.toString() Converts object into a string value. This method is also often
overridden.
Base class
1) a class obtains variables and methods from another class
2) the former is called subclass, the latter super-class (Base class)
3) a sub-class provides a specialized behavior with respect to its super-class
4) inheritance facilitates code reuse and avoids duplication of data
Base class

• One of the pillars of object-orientation.


• A new class is derived from an existing class:
1) existing class is called super-class
2) derived class is called sub-class
• A sub-class is a specialized version of its super-class:
1) has all non-private members of its super-class
2) may provide its own implementation of super-class methods
• Objects of a sub-class are a special kind of objects of a super-class.
Extends Keywod

 A keyword used to inherit a class from another class


 Allows to extend from only one class

class One class Two extends One


{ {
int a=5; int b=10;
} }
Example 1:
Member access rules
• Visibility modifiers determine which class members are accessible and
which do not
• Members (variables and methods) declared with public visibility are
accessible, and those with private visibility are not
• Problem: How to make class/instance variables visible only to its
subclasses?
• Solution: Java provides a third visibility modifier that helps in inheritance
situations: protected
Modifiers and Inheritance
(cont.)
Visibility Modifiers for class/interface:
public : can be accessed from outside the class definition.
protected : can be accessed only within the class definition in which it appears, within
other classes in the same package, or within the definition of subclasses.
private : can be accessed only within the class definition in which it appears.
default-access (if omitted) features accessible from inside the current Java package
The protected Modifier
• The protected visibility modifier allows a member of a base class to be accessed in the child
• protected visibility provides more encapsulation than public does
• protected visibility is not as tightly encapsulated as private visibility

Book
protected int pages
+ getPages() : int
+ setPages(): void

Dictionary

+ getDefinitions() : int
+ setDefinitions(): void
+ computeRatios() : double
Example 2:
Example 3 on BOX
A Superclass Variable Can Reference a Subclass Object

• weightbox is a reference to
BoxWeight objects, and plainbox
is a reference to Box objects.
• Since BoxWeight is a subclass of
Box, it is permissible to assign
plainbox a reference to the
weightbox object
• when a reference to a subclass
object is assigned to a superclass
reference variable, you will have
access only to those parts of the
object defined by the superclass.
• This is why plainbox can’t access
weight even when it refers to a
A Superclass Variable Can Reference
a Subclass Object
• This makes sense, because the superclass has no knowledge of what a
subclass adds to it.
• This is why the last line of code in the preceding fragment is commented
out.
• It is not possible for a Box reference to access the weight field, because
Box does not define one.
Super Keyword
• In the preceding examples, classes derived from Box were not implemented as efficiently or as robustly as they
could have been.
• For example, the constructor for BoxWeight explicitly initializes the width, height, and depth fields of Box.
BoxWeight(double w, double h, double d, double m)
{
width = w;
height = h;
depth = d;
weight = m;
}
• Not only does this duplicate code found in its superclass, which is inefficient, but it implies that a subclass must
be granted access to these members.
• However, there will be times when you will want to create a superclass that keeps the details of its
implementation to itself (that is, that keeps its data members private).
• In this case, there would be no way for a subclass to directly access or initialize these variables on its own. Since
encapsulation is a primary attribute of OOP, it is not surprising that Java provides a solution to this problem.
• Whenever a subclass needs to refer to its immediate superclass, it can do so by use of the keyword super
Example 1: Use of Super in
Constructor
• A subclass can call a constructor
defined by its superclass by use
of the following form of super:
• super(arg-list);
• Here, arg-list specifies any
arguments needed by the
constructor in the superclass.
• super( ) must always be the first
statement executed inside a
subclass’ constructor.
Example 2: User of Super to call the
member of its immediate superclass
• The second form of super acts
somewhat like this, except that it
always refers to the superclass of
the subclass in which it is used.
• This usage has the following
general form:
super.member
• Here, member can be either a
method or an instance variable.
When constructors are executed?
• For example, given a subclass called B
and a superclass called A, is A’s
constructor executed before B’s, or vice
versa?
• The answer is that in a class hierarchy,
constructors complete their execution
in order of derivation, from superclass
to subclass.
• since super( ) must be the first
statement executed in a
subclass’constructor, 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
Method
Overriding
• When a method in a subclass
has the same name and type
signature as a method in its
superclass, then the method in
the subclass is said to override
the method in the superclass.
• When an overridden method
is called from within its
subclass, it will always refer to
the version of that method
defined by the subclass.
• The version of the method
defined by the superclass will
be hidden.
How to also show superclass same
method?
Method
Overloading
• 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.
• For example, consider
this modified version of
the preceding example:
Overloading vs. Overriding

• Overloading deals with • Overriding deals with two


multiple methods in the methods, one in a parent
same class with the same class and one in a child class,
name but different that have the same signature
signatures
• Overloading lets you define oOverriding lets you define a
a similar operation in similar operation in different
different ways for different ways for different object
data types

L 7.7
Dynamic Method Dispatch
• Previous examples in the preceding section demonstrate the mechanics of
method overriding, they do not show its power.
• Indeed, if there were nothing more to method overriding than a name space
convention, then it would be, at best, an interesting curiosity, but of little real
value.
• However, this is not the case.
• Method overriding forms the basis for one of Java’s most powerful concepts:
dynamic method dispatch.
• Dynamic method dispatch is the mechanism by which a call to an overridden
method is resolved at run time, rather than compile time.
• Dynamic method dispatch is important because this is how Java implements
run-time polymorphism
Dynamic Method Dispatch
• Let’s begin by restating an important principle: a superclass reference
variable can refer to a subclass object. Java uses this fact to resolve calls to
overridden methods at run time.
• 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.
• Thus, this determination is made at run time.
• When different types of objects are referred to, different versions of an
overridden method will be called.
• In other words, it is the type of the object being referred to (not the type of
the reference variable) that determines which version of an overridden
method will be executed
Dynamic Method Dispatch
• 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
Class Work on Dynamic Method
Dispatch
• The following program creates a superclass called Figure that stores the
dimensions of a two-dimensional object.
• It also defines a method called area( ) that computes the area of an object.
• The program derives two subclasses from Figure.
• The first is Rectangle and the second is Triangle.
• Each of these subclasses overrides area( ) so that it returns the area of a
rectangle and a triangle, respectively.
Solution:
Abstract Class
• There are situations in which you will want to define a superclass that
declares the structure of a given abstraction without providing a complete
implementation of every method.
• That is, sometimes you will want to create a superclass that only defines a
generalized form that will be shared by all of its subclasses, leaving it to
each subclass to fill in the details.
• Such a class determines the nature of the methods that the subclasses
must implement.
• One way this situation can occur is when a superclass is unable to create a
meaningful implementation for a method.
• This is the case with the class Figure used in the preceding example.
• The definition of area( ) is simply a placeholder. It will not compute and
display the area of any type of object.
Abstract Class (Cont..)
• You can require that certain methods be overridden by subclasses by specifying
the abstract type modifier.
• These methods are sometimes referred to as subclasser responsibility because
they have no implementation specified in the superclass.
• Thus, a subclass must override them—it cannot simply use the version defined in
the superclass.
• To declare an abstract method, use this general form:
abstract type name(parameter-list);
• As you can see, no method body is present.
• Any class that contains one or more abstract methods must also be declared
abstract.
• To declare a class abstract, you simply use the abstract keyword in front of the
class keyword at the beginning of the class declaration
Cautions on Abstract Class
• There can be no objects of an abstract class.
• That is, an abstract class cannot be directly instantiated with the new
operator.
• Such objects would be useless, because an abstract class is not fully defined.
• Also, you cannot declare abstract constructors, or abstract static methods.
• Any subclass of an abstract class must either implement all of the abstract
methods in the superclass, or be declared abstract itself
Previous Example Revisited with
Abstract Class
Three uses of Final Keyword
• Use 1: if you use final before an instance variable it works like a constant you can
not change the value in later methods.
• Use 2: To disallow a method from being overridden, specify final as a modifier at
the start of its declaration.
• Methods declared as final cannot be overridden. The following fragment
illustrates final:
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!"); } }
Three uses of Final Keyword (Cont..)
• Use 3: Sometimes you will want to prevent a class from being inherited. To do this,
precede the class declaration with final. Declaring a class as final implicitly declares
all of its methods as final, too.
• As you might expect, 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.
• Here is an example of a final class:
final class A {
//...
}
// The following class is illegal.
class B extends A { // ERROR! Can't subclass A
//...
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy