0% found this document useful (0 votes)
14 views45 pages

OOP Ch05 Inheritance and Polymorphism

Uploaded by

hoangnam1242004
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views45 pages

OOP Ch05 Inheritance and Polymorphism

Uploaded by

hoangnam1242004
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

CHAPTER 5

Inheritance and Polymorphism

Trinh Thi Van Anh – PTIT


Objectives
• Study concepts: superclass, subclass (Base and derived classes)
• Understand common relationships
• Functions in inheritance
• Using an “instanceof” operator
• Polymorphism
• Overloading
• Overriding
• Interface
• Abstract class
• Anonymous Classes
• Case study
Derived and Super Classes
• Object-oriented languages implement
reusability of coding structure through
inheritance
• It refers to the relationship between classes
where one class inherits the entire structure
of another class
• The root of our design is a relatively abstract
entity, and we build upon that entity to
produce progressively more concrete entities
• the higher-level entities are “parent”, “base”
or “super” classes
• the lower-level ones built from them
are “child”, "derived" or “sub” classes.
Object-Oriented Relationships
• common relationships in classes:
• “is-a/ a kind of”
• “has-a”
• Examples:
• Student is a person
• “A home is a house that has a family and a pet.”
• An invoice contains some products and a product can be
contained in some invoices
Object-Oriented Relationships…
The relation “is-a” is
implemented as a sub- Person The relation “has-a” is
class - String name, address implemented as
Classes Professor, Student are - String birthDate reference
sub-classes of the class Person + String getName();
Sub-classes inherit the + void setName(String n);
…….
structure of super class

is a is a
Student
Professor
- String studentId, majorField
- String department
- String degreeSought
+ String getDepartment(); teach
+ String getStudentId();
+ void setDepartment(String d);
+ void setStudentID(String id)
….
The class Professor has the field The class Student has the
Student[] students field Professor pr
Inheritance
• How to construct a class hierarchy? → Intersection
⚫ Rectangle< length, width>
⚫ Box < length, width, height> Rectangle

Length
width

Box
height
Inheritance…
• Consider a shop that sells antiques items, namely vases, statues and
paintings
Inheritance…
• There are some sub-classes from one super class ➔ An inheritance is
a relationship where objects share a common structure: the structure
of one object is a sub-structure of another object.
• The extends keyword is used to create sub-class.
• A class can be directly derived from only one class
( Java is a single-inherited OOP language).
• If a class does not have any superclass, then it is implicitly derived
from Object class.
• Unlike other members, constructor cannot be inherited (constructor of
super class can not initialize sub-class objects)
“super” Keyword
• Constructors Are Not Inherited
• super(...) for Constructor Reuse
• super(arguments); //invoke a superclass constructor
• Subclass constructor must invoke super class constructor
• The call must be the first statement in the
subclass constructor
• Note: If a constructor does not explicitly invoke a superclass constructor,
the Java compiler automatically inserts a call to the no-argument
constructor of the superclass. If the super class does not have a no-
argument constructor, you will get a compile-time error.
Example
Example…
public class Point {
Example…
private int x,y;
public Point(int x,int y){
this.x=x; this.y=y;}
…..//getter & setter }
public class Polygon {
protected Point d1, d2, d3, d4;
public void setD1(Point d1) {this.d1=d1;}
public Point getD1(){return d1;}
@Override
public String toString(){
return
d1.getX()+"\t"+d1.getY()+"\t"+d2.getX()+"\t"+d2.getY()+
"\t"+d3.getX()+"\t"+d3.getY()+"\t"+d4.getX()+"\t"+d4.getY(); }}
public class Square extends Polygon{
public Square(){
d1 = new Point(0,0); d2 = new Point(0,1);
d3 = new Point (1,0);d4 = new Point(1,1);
}
}
public class Main {
public static void main(String args[]){
Square sq = new Square();
System.out.println(sq.toString());
}
}
public class Main {
public static void main(String
args[]){
Employee e = new Employee();
public class Person {
e.setName("To Ngoc Van");
private String name;
e.setBithday("3/4/1994");
private String bithday;
e.setSalary(4.4);
public Person() { System.out.println(e.toString());
} // getter & setter } }
public class Employee extends Person }{
private double salary;
public double getSalary() { return salary; }
public void setSalary(double salary){
this.salary = salary; }
@Override
public String toString() {
//return name + "\t" + birthday + "\t" + salary;
return super.getName() + "\t" + super.getBithday() +
"\t" + salary;
}
}
1. public class Polygon { Output???
protected Point d1, d2, d3, d4;
public Polygon() {
System.out.println(“Polygon class");
}……}
2. public class Square extends Polygon{
public Square(){
System.out.println(“Square class");
}
}
3. public class Main {
public static void main(String args[]){
Square hv = new Square();
}
}
1. public class Polygon {
protected Point d1, d2, d3, d4;
//a constructor is not default contructor
……}
2. public class Square extends Polygon{
public Square(){
System.out.println(“Square class");
}
}
3. public class Main {
public static void main(String args[]){
Square hv = new Square();
}
}

Why Error???
Functions in inheritance
• A derived class inherits from superclass is limited to the normal member
functions of the superclass.
• We use the Java keyword super as the qualifier for calling a superclass ’s method:
• super.methodName(arguments);
• To invoke the version of method methodName that was defined by our
superclass.
• Hiding a method: Re-implementing a static method implemented in super class
• The "displayDiscount" method has the
same signature (name, plus the number
and the type of its parameters) and return
type as in the superclass. It is called
Output:
overriding the superclass's method=> We
discounting …
will learn override method in the next topic
and taking …
• The "displayDiscount") that was defined by
our superclass. We use
the "super" keyword
Overriding and Hiding Methods (1)
• Overriding a method: An instance method in a subclass with the
same signature (name, plus the number and the type of its
parameters) and return type as an instance method in the superclass
overrides the superclass's method.
• Use the @Override annotation that instructs the compiler that you intend to
override a method in the superclass (you may not use it because overriding is
default in Java).
• Hiding a method: Re-implementing a static method implemented in
super class
Hiding Method
Using an “instanceof” operator
• Dynamic and Static type
▪ dynamic type: A reference variable that has the type of the superclass
can store the address of the object of sub class. It is called to
be dynamic type, the type that is has at runtime.
Rectangle obj1 = new Box();
▪ Static type: The type that it has when first declared. Static type checking
is enforced by the compiler.
Box obj2 = new Box();
• “Instanceof” operator: It checks whether the reference of an object
belongs to the provided type or not, the instanceof operator will return
true or false.
If ( obj1 instanceof Box)
System.out.println(“ obj1 is pointing to the Box object”);
Casting
• A variable that has the type of the superclass only calls methods of
the superclass. To call methods of the subclass we must cast explicitly
• for example,
Rectangle obj = new Box();
((Box)obj).setHeight(300);
Polymorphism
• The dictionary definition of polymorphism refers to a principle in
biology in which an organism or species can have many different
forms or stages.
• Polymorphism was perfected in object-oriented languages
• Ability allows many versions of a method based on overloading
and overriding methods techniques.
• Overloading: A class can have some methods which have the
same name but their parameter types are different.
• Overriding: A method in the father class can be overridden in
its derived classes (body of a method can be replaced in
derived classes).
Overloading
• overloading with constructors
public Rectangle(){…}
Rectangle
public Rectangle(int length,
# length: int int width){… }
# width: int
• Overloading also extends to general methods.
+ Rectangle();
public void setValue(int len){
+ Rectangle(int, int) length= (len>0)?1:0;
+ setValue(int): void }
+ setValue(int, int): void public void setValue (int len,
int wi){
length= (len>0)? 1: 0;
width= (wi>0)? wi:0;
}
Overriding
• A subclass provides the specific implementation of the method that
has been declared by one of its pare
• Subclasses of a class can define their own unique behaviors and yet
share some of the same functionality of the parent class.
Student

- String name;
+ void print();

GraduateStudent UndergraduateStudent

- String underGraduateDegree; - String highSchool;

+ GraduateStudent(String n, String ug) + UndergraduateStudent(String n, String h)


+ void print(); + void print ();
How Can Overridden Method be Determined?
Interfaces
• An interface is a reference type, similar to a class, that can
contain only constants, initialized fields, static methods, prototypes (abstract
methods, default methods), static methods, and nested types.
• It will be the core of some classes
• Interfaces cannot be instantiated because they have no-body methods.
• Interfaces can only be implemented by classes or extended by other
interfaces.
• WHY AND WHEN TO USE INTERFACES?
• Objects define their interaction with the outside world through the
methods that they expose
• Java does not support "multiple inheritance" (a class can only inherit from
one superclass). However, it can be achieved with interfaces, because the
class can implement multiple interfaces
Interfaces…
Interfaces…

m3(), m4() in A cannot


implement m3(), m4()
in InterfaceDemo,
attempting to assign
weaker access
privileges, were public

Default methods of an interface must be overridden as public methods in


concrete classes.
Example: how to create an interface
Example:implement an interface
Output:
set lock in the default method
on TV
off TV
shut down after 10000 seconds
TV remote's price:10
TV Remote has: 20buttons
Example: multiple interfaces

Output:
set lock in the default method
on TV
off TV
shut down after 10000 seconds
TV remote's price:10
TV Remote has: 20buttons
increase volumn
Example: how to extend interfaces

Output:
on AC
display Korean
set lock in the
default method
Abstract Classes
• Used to define what behaviors a class is required to perform without
having to
provide an explicit implementation.
• It is the result of so-high generalization
• Syntax to define a abstract class
• public abstract class className{ ... }
• It isn’t necessary for all of the methods in an abstract class to be
abstract.
• An abstract class can also declare implemented methods.
Abstract Classes…

Modified
Abstract Classes…

This class have no abstract method but it is declared as an


abstract class. So, we can not initiate an object of this class.
Abstract Classes…

Error. Why?
Implementing Abstract Methods
• Derive a class from an abstract superclass, the subclass will inherit all
of the superclass’s
features, all of abstract methods included.
• To replace an inherited abstract method with
a concrete version, the subclass need merely override it.
• Abstract classes cannot be instantiated
Anonymous Classes
Anonymous classes are classes which are not named but they are
identified automatically by Java compiler.
Where are they? They are identified at initializations of
interface/abstract class object but abstract methods are implemented
as attachments.
Why are they used?
• Enable you to make your code more concise.
• Enable you to declare and instantiate a class at the same time.
• They are like local classes except that they do not have a name.
• Use them if you need to use a local class only once.
Anonymous Class

Anonymous class.

Class name is given by the


compiler:
ContainerClass$Number
Anonymous Class…
Concrete methods but they can
not be used because the class is
declared as abstract one.

The abstract class can be used


only when at least one of it’s
methods is overridden

Anonymous class is a technique is commonly used to support


programmer when only some methods are overridden only
especially in event programming.
Case study
• A antique shop that sells antique items, namely vases, statues, and
paintings. The owner can add item to inventory. The shop will keep
items in the list. The owner can add a new item to it, he search also
the item,….
• =>For now, we want to manage the list of objects such as vases,
statues, paintings in an array or a list.
Summary
• Object-oriented languages implement reusability of coding structure
through inheritance
• A derived class does not by default inherit the constructor of a super
class
• Constructors in an inheritance hierarchy execute in order from the
super class to the derived class
• Using the instanceof keyword if we need to check the type of the
reference variable.
• Check the type of the reference variable before casting it explicitly.
• Polymorphism is a concept of object-oriented programming
• Polymorphism is the ability of an object to take on many forms
• Overloading and overriding are a technology to implement
polymorphism feature.
• In OOP occurs when a parent class/ interface reference is used to
refer to a child class object

You might also like