Java Inheritance and Classes: Understanding Parent-Child Relationships, Papers of Data Structures and Algorithms

An in-depth exploration of inheritance in java, a fundamental technique used to create reusable classes. Learn how to derive a new class from an existing one, the concept of is-a relationship, and the use of protected modifier. Discover the difference between multiple inheritance and overriding methods, as well as the importance of class hierarchies and abstract classes.

Typology: Papers

Pre 2010

Uploaded on 08/16/2009

koofers-user-urk
koofers-user-urk 🇺🇸

10 documents

1 / 6

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
8.1 – Inheritance
Inheritance is a fundam ental technique
Inheritance is a fundam ental technique
used to create and organize
used to create and organize reusable
reusable cla sses
classes
Inheritance
Inheritance allows a software developer
allows a softwar e developer
to derive a new class from an existing one
to derive a new class from an existing one
The existing class is c alled
The existing class is c alled
the
the parent c lass,
parent class, or
or super class
superclass
The derived class is ca lled
The derived class is ca lled
the
the child cla ss
child class or
or subc lass
subclass
As the name implies,
As the name implies,
the child
the child in herits
inherits c haracteristics of the parent
characteristics of the parent
(the methods and data defined by the parent class)
(the methods and data defined by the parent class)
Proper inheritance cre ates an
Proper inheritance cre ates an is-a
is-a relat ionship:
relationship:
=> the child
=> the child is a
is a more specif ic version of the parent
more specific version of the parent
1-1
8.1 – Inheritance
A programmer can tail or a derived class as needed
by adding new varia bles or methods,
or by modifying t he inherited ones
By using existing com ponents to create new ones,
we capitalize on all the effort that went
into the design, implem entation, and testing of the existin g
software
extends is used to establish a n is-a (inheritance) relationship
1-2
class Car extends Vehicle
{
// class contents
}
8.1 – Class Diagram for Words
1-3
Inheritance symbol
8.1 – Words.java
1-4
//********************************************************************
// Words.java Java Foundations
//
// Demonstrates the use of an inherited method.
//********************************************************************
public class Words
{
//-----------------------------------------------------------------
// Instantiates a derived class and invokes its inherited and
// local methods.
//-----------------------------------------------------------------
public static void main (String[] args)
{
Dictionary webster = new Dictionary();
System.out.println ("Number of pages: " + webster.getPages()) ;
System.out.println ("Number of definitions: " +
webster.getDefinitions());
System.out.println ("Definitions per page: " +
webster.computeRatio());
}
}
8.1 – Book.java
1-5
//********************************************************************
// Book.java Java Foundations
//
// Represents a book. Used as the parent of a derived class to
// demonstrate inheritance.
//********************************************************************
public class Book
{
protected int pages = 1500;
//----------------------------------------------------------------
// Pages mutator.
//----------------------------------------------------------------
public void setPages (int numPages)
{
pages = numPages;
}
//----------------------------------------------------------------
// Pages accessor.
//----------------------------------------------------------------
public int getPages ()
{
return pages;
}
}
8.1 – Dictionary.java
1-6
//********************************************************************
// Dictionary.java Java Foundations
// Represents a dictionary, which is a book. Used to demonstrate inheritance.
//********************************************************************
public class Dictionary extends Book
{
private int definitions = 52500;
// Computes ration of definitions per page
public double computeRatio () // to demo use of parent vars
{
return definitions/pages;
}
// Setter aka mutator
public void setDefinitions (int numDefinitions)
{
definitions = numDefinitions;
}
// Setter aka. accessor
public int getDefinitions ()
{
return definitions;
}
}
pf3
pf4
pf5

Partial preview of the text

Download Java Inheritance and Classes: Understanding Parent-Child Relationships and more Papers Data Structures and Algorithms in PDF only on Docsity!

8.1 – Inheritance

Inheritance is a fundamental techniqueInheritance is a fundamental technique

used to create and organizeused to create and organize reusablereusable classesclasses

InheritanceInheritance allows a software developerallows a software developer

to derive a new class from an existing oneto derive a new class from an existing one

The existing class is calledThe existing class is called

thethe parent class,parent class, oror superclasssuperclass

The derived class is calledThe derived class is called

thethe child classchild class oror subclasssubclass

As the name implies,As the name implies,

the childthe child^ inheritsinherits^ characteristics of the parentcharacteristics of the parent

(the methods and data defined by the parent class)(the methods and data defined by the parent class)

Proper inheritance creates anProper inheritance creates an^ is-ais-a^ relationship:relationship:

=> the child=> the child^ is ais a^ more specific version of the parentmore specific version of the parent

8.1 – Inheritance

A programmer can tailor a derived class as needed

by adding new variables or methods,

or by modifying the inherited ones

By using existing components to create new ones,

we capitalize on all the effort that went

into the design, implementation, and testing of the existing

software

extends is used to establish an is-a (inheritance) relationship

class Car extends Vehicle

// class contents

8.1 – Class Diagram for Words

Inheritance symbol

8.1 – Words.java

//******************************************************************** // Words.java Java Foundations // // Demonstrates the use of an inherited method. //******************************************************************** public { class Words //----------------------------------------------------------------- // Instantiates a derived class and invokes its inherited and // //----------------------------------------------------------------- local methods. public { static void main (String[] args) Dictionary webster = new Dictionary(); System.out.println ("Number of pages: " + webster.getPages()); System.out.println ("Number webster (^) .ofgetDefinitions definitions:()); " + System.out.println ("Definitions webster.computeRatio per page:()); " + }^ }

8.1 – Book.java

//******************************************************************** // Book.java Java Foundations // // Represents a book. Used as the parent of a derived class to // //******************************************************************** demonstrate inheritance. public { class Book protected int pages = 1500; //---------------------------------------------------------------- // Pages mutator. //---------------------------------------------------------------- public void setPages (int numPages) { pages = numPages; } //---------------------------------------------------------------- // Pages accessor. //---------------------------------------------------------------- public int getPages () { return pages; }^ }

8.1 – Dictionary.java

//******************************************************************** // Dictionary.java Java Foundations // //******************************************************************** Represents a dictionary, which is a book. Used to demonstrate inheritance. public { class Dictionary extends Book private int definitions = 52500; // public Computes double ration computeRatio of definitions () per page// to demo use of parent vars { return definitions/pages; } // public Setter void aka setDefinitions mutator (int numDefinitions) { definitions = numDefinitions; } // public Setter int akagetDefinitions. accessor () { return definitions; }^ }

8.1 – The protected Modifier

A protected variable is visible

to any class in the same package as the parent class

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

Protected variables and methods can be shown with a # symbol

preceding them in UML diagrams

8.1 – The super Reference

Constructors are not inherited,

even though they have public visibility

Yet, we often want to use the parent's constructor

to set up the “parent's part” of the object

The super reference can be used to refer to the parent class,

and often is used to invoke the parent's constructor

8.1 – Words2.java

//******************************************************************** // Words2.java Java Foundations // // Demonstrates the use of the super reference. //******************************************************************** public { class Words //----------------------------------------------------------------- // Instantiates a derived class and invokes its inherited and // //----------------------------------------------------------------- local methods. public { static void main (String[] args) Dictionary2 webster = new Dictionary2 (1500, 52500); System.out.println ("Number of pages: " + webster.getPages()); System.out.println ("Number webster (^) .ofgetDefinitions definitions:()); " + System.out.println ("Definitions webster.computeRatio per page:()); " + }^ }

8.1 – Book2.java

//******************************************************************** // Book2.java Java Foundations // // Represents a book. Used as the parent of a derived class to // //******************************************************************** demonstrate inheritance and the use of the super reference. public { class Book protected int pages; public { Book2 (int numPages) // Constructor (to be invoked by child) }^ pages^ =^ numPages; public { void setPages (int numPages) pages = numPages; } public { int getPages () }^ return^ pages; }

8.1 – Dictionary2.java

//******************************************************************** // Dictionary2.java Java Foundations // // Represents a dictionary, which is a book. Used to demonstrate // //******************************************************************** the use of the super reference. public { class Dictionary2 extends Book private int definitions; //----------------------------------------------------------------- // Constructor: Sets up the dictionary with the specified number // //----------------------------------------------------------------- of pages and definitions. public { Dictionary2 (int numPages, int numDefinitions) super(numPages); }^ definitions^ =^ numDefinitions; (etc for computeRatio(), setDefinitions(), getDefinitions()…)

8.1 – The super Reference

A child’s constructor is responsible

for calling the parent’s constructor

The first line of a child’s constructor

should use the super reference to call the parent’s constructor

If the child does not call super ,

a 0-parameters super constructor will be called anyway!

The super reference can also be used

to reference other variables & methods defined in parent’s class

8.2 – Overloading vs. Overriding

Overloading deals with multiple methods with the same name in

the same class, but with different signatures

Overriding deals with two methods, one in a parent class and

one in a child class, that have the same signature

Overloading lets you define a similar operation in different ways

for different parameters

Overriding lets you define a similar operation in different ways

for different object types

8.3 – Class Hierarchies

A child class of one parent can be the parent of another child, forming a

class hierarchy

Two children of the same parent are called siblings

Common features should be put as high in the hierarchy as is reasonable

An inherited member is passed continually down the line

 Therefore, a child class inherits from all its ancestor classes 1- 20

8.3 – An Alternate Class Hierarchy

There is no single class hierarchy that is appropriate for all situations

8.3 – The Object Class

A class called Object is defined

in the java.lang package of the Java standard class library

All classes are derived from the Object class

If a class is not explicitly defined

to be the child of an existing class,

it is assumed to be the child of the Object class

Therefore, the Object class

is the ultimate root of all class hierarchies

8.3 – The Object Class’ Methods

The Object class contains a few useful methods,

which are inherited by all classes

I.e., the toString() method is defined in the Object class

Every time we define the toString method,

we are actually overriding an inherited definition

The toString method in the Object class

is defined to return a string that contains

the name of the object’s class along with some other information

Also in Object :

equals() returns T iff ___________

clone() returns ___________

8.3 – Abstract Classes

An abstract class is a placeholder in a class hierarchy

that represents a generic concept

An abstract class cannot be instantiated

To declare a class as abstract:

Abstract classes are an important element of software design:

they allow us to establish common elements in a hierarchy

that are too generic to instantiate

public abstract class Vehicle

// contents

8.3 – Abstract Classes: Rules

An abstract class often contains abstract methods with no definitions

 The abstract modifier must be applied to each abstract method

An abstract class typically contains non-abstract methods with full definitions

A class declared as abstract does not have to contain abstract methods –

simply declaring it as abstract makes it so

The child of an abstract class must override the abstract methods of the

parent,

or it, too, will be considered abstract

An abstract method cannot be defined as final or static

8.3 – An Abstract Class in UML

Abstract classes

and methods are

shown in italics font.

8.4 – Visibility Revisited

It's important to understand one subtle issue related to inheritance

and visibility

All variables and methods of a parent class are inherited by its

children, even private members.

Private members cannot be referenced by name in the child class

However, they can be referenced indirectly using its parent's

methods

The super reference can be used to refer to the parent class,

even if no object of the parent is explicitly created

8.4 – FoodAnalyzer.java

//******************************************************************** // FoodAnalyzer.java Java Foundations // // Demonstrates indirect access to inherited private members. //******************************************************************** public { class FoodAnalyzer //----------------------------------------------------------------- // Instantiates a Pizza object and prints its calories per // //----------------------------------------------------------------- serving. public { static void main (String[] args) Pizza special = new Pizza (275); System.out.println ("Calories special.caloriesPerServing per serving: " +()); }^ }

8.4 – Pizza.java

//******************************************************************** // Pizza.java Java Foundations // // Represents a pizza, which is a food item. Used to demonstrate // //******************************************************************** indirect referencing through inheritance. 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); }

8.4 – FoodItem.java

//******************************************************************** // FoodItem.java Java Foundations // // Represents an item of food. Used as the parent of a derived class // //******************************************************************** to demonstrate indirect referencing. public { class FoodItem final private private int fatGrams; int CALORIES_PER_GRAM = 9; protected int servings; //----------------------------------------------------------------- // Sets up this food item with the specified number of fat grams // //----------------------------------------------------------------- and number of servings. public { FoodItem (int numFatGrams, int numServings) fatGrams servings == numFatGrams;numServings; } (more…)