Inheritance Unit 2
Inheritance Unit 2
Inheritance
• Inheritance is a fundamental object-oriented
design technique used to create and organize
reusable classes
• Focuses on:
deriving new classes from existing classes
the protected modifier
creating class hierarchies
abstract classes
indirect visibility of inherited members
designing for inheritance
Outline
Creating Subclasses
Overriding Methods
Class Hierarchies
Inheritance and Visibility
Designing for Inheritance
Inheritance
• Inheritance allows a software developer to
derive a new class from an existing one
• The existing class is called the parent class, or
superclass, or base class
• The derived class is called the child class or
subclass
• As the name implies, the child inherits
characteristics of the parent
• That is, the child class inherits the methods and
data defined by the parent class
Inheritance
• Inheritance relationships are shown in a UML
class diagram using a solid arrow with an
unfilled triangular arrowhead pointing to the
parent class
Vehicle
Car
class Animal
{
// eat() method
// sleep() method
}
class Dog extends Animal
{
// bark() method
}
Deriving Subclasses
Deriving Subclasses
is-a relationship
Inheritance is an is-a relationship. We use
inheritance only if an is-a relationship is present
between the two classes.
• SINGLE INHERITANCE
• MULTIPLE INHERITANCE(Not supported in Java)
• MULTI LEVEL INHERITANCE
• HIERARCHICAL
• HYBRID INHERITANCE(Not supported in Java)
TYPES OF INHERITANCE
• SINGLE INHERITANCE
• MULTIPLE INHERITANCE
• MULTI LEVELINHERITANCE
• HIERARCHICAL INHERITANCE
• HYBRID INHERITANCE
Output:
Class Car
Class Maruti
Maruti Model: 800
Vehicle Type: Car
Brand: Maruti
Max: 80Kmph
class JavaExample {
public static void main(String args[])
{
B obj1 = new B();
C obj2 = new C();
D obj3 = new D(); //All classes can access the method
of class A
obj1.methodA();
obj2.methodA();
obj3.methodA(); } }
HIERARCHICAL INHERITANCE
• Output:
• method of Class A
• method of Class A
• method of Class A
The protected Modifier
• Visibility modifiers affect the way that class
members can be used in a child class
• Variables and methods declared with private
visibility cannot be referenced by name in a
child class
• They can be referenced in the child class if they
are declared with public visibility -- but public
variables violate the principle of encapsulation
• There is a third visibility modifier that helps in
inheritance situations: protected
The protected Modifier
• The protected modifier allows a child class to
reference a variable or method directly in the
child class
• It provides more encapsulation than public
visibility, but is not as tightly encapsulated as
private visibility
• A protected variable is visible to any class in the
same package as the parent class
• Protected variables and methods can be shown
with a # symbol preceding them in UML diagrams
The protected Modifier
Here's a summary from where access modifiers can
be accessed.
//-------------------------------------------------------
---
// Sets up this food item with the specified number of
fat
// grams and number of servings.
//-------------------------------------------------------
---
public FoodItem (int numFatGrams, int numServings)
{
fatGrams = numFatGrams;
servings = numServings;
}
FoodItem.java
//-------------------------------------------------------
---
// Computes and returns the number of calories in this
food
// item due to fat.
//-------------------------------------------------------
---
private int calories()
{
return fatGrams * CALORIES_PER_GRAM;
}
//-------------------------------------------------------
---
// Computes and returns the number of fat calories per
// serving.
//-------------------------------------------------------
---
public int caloriesPerServing()
{
return (calories() / servings);
}
}
Pizza.java
public class Pizza extends FoodItem
{
//-------------------------------------------------------
---
// Sets up a pizza with the specified amount of fat
// (assumes eight servings).
//-------------------------------------------------------
---
public Pizza (int fatGrams)
{
super (fatGrams, 8);
}
}
FoodAnalyzer.java
public class FoodAnalyzer
{
//-------------------------------------------------------
---
// Instantiates a Pizza object and prints its calories
per
// serving.
//-------------------------------------------------------
---
public static void main (String[] args)
{
Pizza special = new Pizza (275);
Business
RetailBusines ServiceBusine
s ss
Creating Subclasses
Overriding Methods
Class Hierarchies
Designing for Inheritance
Designing for Inheritance
• As we've discussed, taking the time to create a
good software design reaps long-term benefits
• Inheritance issues are an important part of an
object-oriented design
• Properly designed inheritance relationships can
contribute greatly to the elegance,
maintainability, and reuse of the software
• Let's summarize some of the issues regarding
inheritance that relate to a good software design
Inheritance Design Issues
• Every derivation should be an is-a relationship
• Think about the potential future of a class
hierarchy, and design classes to be reusable
and flexible
• Find common characteristics of classes and
push them as high in the class hierarchy as
appropriate
• Override methods as appropriate to tailor or
change the functionality of a child
• Add new variables to children, but don't redefine
(shadow) inherited variables
Inheritance Design Issues
• Allow each class to manage its own data; use
the super reference to invoke the parent's
constructor to set up its data
• Even if there are no current uses for them,
override general methods such as toString
and equals with appropriate definitions
• Use abstract classes to represent general
concepts that lower classes have in common
• Use visibility modifiers carefully to provide
needed access without violating encapsulation
Restricting Inheritance
• The final modifier can be used to curtail
inheritance
• If the final modifier is applied to a method,
then that method cannot be overridden in any
descendent classes
• If the final modifier is applied to an entire
class, then that class cannot be used to derive
any children at all
Thus, an abstract class cannot be declared as final