(Inheritance&Polymorphism Concepts of Java) PDF
(Inheritance&Polymorphism Concepts of Java) PDF
PROGRAMMING
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:
26
instanceof
27
4. Abstract
classes and
methods
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.
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!
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