Creating Classes From Other Classes
Creating Classes From Other Classes
Classes
Chapter 2
Chapter Contents
Composition
• Adapters
Inheritance
• Invoking constructors from within constructors
• Private fields and methods of the base class
• Overriding, overloading methods
• Protected access
• Multiple inheritance
• Type compatibility and base classes
• The class Object
• Abstract classes and methods
Polymorphism
2
Composition
When a class has a data field that is an
instance of another class
Example – an object of type Student.
AA"has
"has a"
a"
relationship
relationship
fig 2-1
4
Inheritance
A general or base class is first defined
Then a more specialized class is defined
by …
• Adding to details of the base class
• Revising details of the more general class
Advantages
• Saves work
• Common properties and behaviors are define
only once for all classes involved
5
Inheritance
An
An"is
"isa"
a"
relationship
relationship
9
Overriding Methods
When a derived class defines a method with the
same signature as in base class
• Same name
• Same return type
• Same number, types of parameters
14
Protected Access
A method or data field modified by
protected can be accessed by name
only within
• Its own class definition
• Any class derived from that base class
• Any class within the same package
15
Protected Access
17
Object Types of a Derived Class
Given :
• Class CollegeStudent,
• Derived from class Student
19
Abstract Classes and Methods
Some base classes are not intended to have
objects of that type
• The objects will be of the derived classes
21
Polymorphism
Which displayAt is called …
• Depends on the invoking object's place in the
inheritance chain and is not determined by the type of
the variable naming the object