Вы находитесь на странице: 1из 48

CSC584 – ENTERPRISE

PROGRAMMING

CHAPTER 1 – INHERITANCE & POLYMORPHISM


Masurah Mohamad
Inheritance & Polymorphism concept
Inheriting instances fields and methods
Chapter
Method overriding
overview
Access levels – public, protected, private
Abstract super classes and methods
Interface
Inheritance concept
Access levels – public, protected, private
and package
INHERITANCE
Inheriting instance fields and methods
scopes
Calling super class constructors and
methods
Object class
 Inheritance is a form of software reusability in which new classes are
created from existing classes. The new class inherits the data member and
methods of the existing classes.
 The existing class is called superclass/base class/parent class
 The derived class is called subclass/derived class/child class
 A subclass may inherit the data and the behavior of its superclass
Inheritance
 When one object is a specialized version of another object, there is an “is-
concept a“ relationship between them.
 Without having to rewrite the class, a subclass inherits all the features
For example : a car is a (data members and methods but not the constructors) from the
vehicle, a truck is a superclass.
vehicle.  A subclass can creates new data and new methods.
 A subclasses usually have more functionality than their super class.
Inheritance
terminology
1) The private members of the superclass are private to the
superclass.
2) The subclass can directly access the public members of the
superclass.
3) The subclass can include additional data and method
members.

Inheritance 4) The subclass can override (redefine) the public methods of


the superclass. However, this redefinition applies only to the
rules objects of the subclass, not to the objects of the superclass.
(Superclass CANNOT access instance fields and methods of
subclass)
5) All data members of the superclass are also data members
of the subclass. Similarly, the methods of the superclass
(unless overridden) are also the methods of the subclass.
(Remember Rule 1 when accessing a member of the
superclass in the subclass.)
A sub class does not inherit private
members of its parent class
1. Inheriting  Private data fields in a super class are
instance fields not accessible outside the class.
and methods Can’t be used directly in a sub class.
Can be accessed (mutated) through
public accessor if defined in super class.
Final modifier
To override a public method of
the superclass in the subclass,
the corresponding method in the
2. Method subclass must have same:
Overriding Name
Type
Formal parameter list
Overriding - If the corresponding method
in the superclass and the subclass has the
same name and same parameter lists.
Overloading - If the corresponding
method in the superclass and the subclass
has the same name but different
2. Method parameter lists.
Overriding When override or overload a method of
the superclass in the subclass, you must
know how to specify a call to the method
of the superclass that has the same name
as that used by a method of the subclass.
3. Access
levels
The accessibility of a protected member
3. Access of a class falls between public and
levels private.
------ Applied if a member of superclass needs
Protected to be directly accessed in a subclass and
Members of a still need to prevent its direct access
Class outside the class
1
public class BClass
EXAMPLE {
protected char bCh;
private double bX; 2
public void setData(double u)
3. Access public BClass()
{
{
bX = u;
levels bCh = “*”;
}
bX = 0.0;
------ }
public void setData(char ch, double u)
{
Protected public BClass(char ch, double u)
{
bCh = ch;
Members of a bCh = ch;
}
bX = u;
bX = u;
Class }
public String toString()
{
return (“Superclass: bCh = ” +
bCh + “, bX = “ + bX + ‘\n’);
}
}
3. Access levels
------
3 Protected Members of a Class (cont.)
public class DClass extends BClass
{
private int dA;
4
public DClass() public void setData(char ch, double v, int a)
{ {
super(); super.setData(v);
dA = 0; bCh = ch;
} dA = a;
public DClass(char ch, double v, int a) }
{ public String toString()
super(ch, v); {
dA = a; return(super.toString() + “Subclass dA = ” + dA + ‘\n’);
} }
}
5
public void setData(char ch, double v, int a)
{
3. Access super.setData(v);
levels bCh = ch;
------ dA = a;
Protected }
Members of a public String toString()
Class (cont.) {
return(super.toString() + “Subclass dA = ” + dA + ‘\n’);
}
6
 Following program shows how the objects of BClass and DClass
work:
public class ProtectedMemberProg
{
3. Access public static void main(String[] args)
levels {
------ BClass bObject = new BClass();
DClass dObject = new DClass();
Protected
Members of a System.out.println(bObject);
dObject.setData(‘&’, 2.5, 7);
Class (cont.) System.out.println(dObject);
}
} Output
Superclass: bCh = *, bX = 0.0
Superclass: bCh = &, bX = 2.5
Subclass dA = 7
• Polymorphism concept
• Abstract super classes and methods
Polymorphism • Interface
• Concrete sub classes and methods
Polymorphism allows a single variable to
refer to objects from different subclasses in
the same inheritance hierarchy
For example, if Cat and Dog are subclasses
Polymorphism of Pet, then the following statements are
valid:
concept
If Student and Staff are subclasses of Person,
then the following statements are valid:

Polymorphism
example
Example

Superclass :
PersonPoly

21
Example

Subclass:
StudentPoly

22
Example

Subclass:
EmployeePoly

23
Example

Main class

24
 The instanceof operator can help us learn the
class of an object.
The instanceof  Determines whether a reference variable that
method points to an object is of a particular class type.

 Syntax:

Example; the following <variable> instanceof <className>


code counts the number of Example: p instanceof BoxShape
undergraduate students:  This expression evaluates to true if p points to an
object of the class BoxShape; otherwise it
evaluates to false:
Example:
instanceof

26
instanceof

Use cast operator to make sure p[i] points


to an object of subclass EmployeePoly
Example:
instanceof
(cont.)

27
4. Abstract
classes and
methods

 When define a superclass, we often do


not need to create any instances of the
superclass.
 Depending on whether we need to
create instances of the superclass, we
must define the class differently.
 An abstract class is a class:
defined with the modifier abstract (declared with the reserved
word abstract in its heading)
OR
that contains an abstract method
OR
that does not provide an implementation of an inherited
4. ABSTRACT abstract method

CLASS
 An abstract method is a method with the keyword
abstract, and it ends with a semicolon instead of a method
body.
 Private methods and static methods may not be declared abstract.

 No instances can be created from an abstract class.


 An abstract class can contain instance variables,
constructors, *finalizers, and non-abstract methods.
4.
 An abstract class can contain abstract methods.
ABSTRACT
 If a class contains an abstract method, the class
CLASS must be declared abstract.
(cont.)
 You cannot instantiate an object of an abstract class
type. You can only declare a reference variable of an
abstract class type.
*Finalizer is a void method. A class can
have only 1 finalizer. Finalizer can’t
 You can instantiate an object of a subclass of an
have any parameters. Name of finalizer abstract class, but only if the subclass gives the
is finalize. Finalize automatically definitions of all the abstract methods of the
executes when class object goes out of
scope (to free up the memory superclass.
allocated by the object of the class)
4.
ABSTRACT
CLASS
(cont.)
4. ABSTRACT
CLASS (cont.)
4. Abstract
methods
 Used only as super classes in inheritance
hierarchies
 Cannot be used to instantiate objects —
abstract classes are incomplete.
 Subclasses must declare the “missing pieces”
4. Abstract to become “concrete” classes, from which you
can instantiate objects; otherwise, these
super classes subclasses, too, will be abstract.
 An abstract class provides a superclass from
which other classes can inherit and thus share a
common design.
 Used to provide as a template or design for
concrete subclasses down the inheritance tree
 Example
abstract class Card
{
4. Abstract String recipient; // name of who gets the card
classes and public abstract void greeting(); // abstract greeting()
method
methods
}

The abstract class can include abstract methods and non-abstract methods. If a class
contains even one abstract method, then the class itself has to be declared to be abstract.
The definition of greeting() Holiday inherits the abstract
must match the signature class Holiday extends Card method greeting() from its parent.
given in the parent. Holiday must define a greeting()
{ public Holiday( String r ) method that includes a method
body (statements between braces).
{ recipient = r; }
public void greeting()
4. Abstract {
classes and System.out.println("Dear “ + recipient + ",\n");
methods
System.out.println("Season's Greetings!\n\n");
}
}
Holiday is a non abstract child of an abstract parent. Objects can be instantiated from it.
Its constructor implicitly calls the no-argument constructor in its parent, Card, which calls the
constructor in Object
Condition that need to be considered!

4. Abstract  If Holiday did not define greeting(), then Holiday


would be declared an abstract class.
classes and  This would make it an abstract child of an
methods abstract parent.
Advantage of using an abstract class
4. Abstract You can group several related classes
classes and together as siblings.
methods To keep a program organized and
understandable.
Method
overriding
of abstract
classes &
methods
Method
overriding
(cont.)
 A non-abstract child must override each abstract
method inherited (all abstract methods) from its
parent by defining a method with the same
Abstract signature and same return type.
classes and  This is called concrete subclasses, used to emphasize
methods : the fact that it is not abstract.
Method  A child may define additional methods with
signatures different from the parent's method.
overriding  It is an error if a child defines a method with the
same signature as a parent method, but with a
different return type.
Superclass

Subclass
Method
overriding :
Example
Method
override

42
Subclass

Method
overriding : Method override
Example
Method override

43
A class that contains only abstract methods
and/or named constants.
How Java implements multiple inheritance.
To be able to handle a variety of events, Java
5. Interfaces allows a class to implement more than one
interface.
An interface can only extend other
interfaces, but not classes.
5. Interfaces
Interface
vs
abstract class
Write the definition for the super and subclass
below:
 Super class: Car (abstract)
 2 attributes:(name and color)
 2 abstract methods: (display:void and
calculate_price:double)
 Sub class: Perodua (non abstract)
Exercise  2 attributes: price and tax
 Overrides abstract methods (display() and calculate
price())
 display() : to display the information of perodua cars
including total price
 calculate_price() : to calculate total price of car after adding
tax into car price.
 Main method: test the program to display the
output.
47
 Wu, An Introduction To Object-Oriented Programming
With Java, 4th Edition, McGraw-Hill, 2006.
 Core Java®, Volume I—Fundamentals, 10, Prentice Hall,
References 2016, ISBN: 978-013417729

48

Вам также может понравиться