Polymorphism in Java Methods and polymorphic algorithms applied to computer games
Polymorphism in Java Methods and polymorphic algorithms applied to computer games
JAVA
POLYMORPHISM IN
JAVA
Methods and polymorphic algorithms
applied to computer games
Advanced level
Book information:
Title: Polymorphism in Java
Edition: 1st edition 2018
Author: Carlos Alberto Privitera
ISBN-13: 978-1725953420
ISBN-10: 1725953420
Date of the first edition: spring 2018
To my children
Foreword
This book stands out for teaching programming based on polymorphism. Abundant examples in
Java code and illustrative graphics of the main ideas related to the topic: Polymorphism in Java.
The book "Polymorphism in Java" aims to give a modern and updated vision when learning Java
and in the particular subject of polymorphic algorithms. Students, teachers and developers will be
able to find a sequence of design patterns that create and use polymorphic algorithms, these
design patterns can be applied to solving problems of computer systems and everyday life.
A professional in the Java language can benefit from the book "Polymorphism in Java" by finding
an innovative way to solve problems with polymorphic algorithms. The design patterns, analyzed
in this work, are based on the inheritance between classes. Currently the difficulties of the Java
language have been overcome to a large extent and it is easy to understand and apply.
The book aims to teach fundamental concepts of object-oriented programming with Java SE, in a
clear and practical way, significantly reducing the learning curve. In the process you will learn to
program computers and use the Java SE language.
Goals:
The present work aims that readers get strong knowledge in computer programming with the
Java SE language.
Get the reader to acquire practical skills by using advanced Java SE concepts.
Have the reader write computer programs based on object-oriented programming with the
Java SE language.
Level of the book: it is of advanced level. It requires knowledge of the basic details of the Java SE
language.
Content
Chapter I .......................................................................................................................................................... 13
Introduction ................................................................................................................................................. 13
Proposal for a basic architecture .............................................................................................................. 13
Design pattern based on inheritance ............................................................................................................ 14
Layered architecture to use a design pattern ............................................................................................... 15
Description of the design pattern based on the inheritance ......................................................................... 16
Types of relations between classes........................................................................................................... 16
Java has a keyword to declare each relationship ...................................................................................... 16
Criteria for building groups of configurations of patterns of architectures by layers ..................................... 16
What are abstract methods? .................................................................................................................... 16
What are abstract classes? ....................................................................................................................... 16
What is an interface? ............................................................................................................................... 16
There are two ways to declare abstract methods: .................................................................................... 17
How to overwrite methods that are abstract? .......................................................................................... 17
Criteria for assembling the different configurations of a design pattern ................................................... 17
What is a reference in Java? ..................................................................................................................... 17
What is an object in Java? ........................................................................................................................ 17
Structure of the book ................................................................................................................................... 18
Graphical representation of the groups of configurations of a design pattern .......................................... 18
Group number one of configurations ........................................................................................................... 19
Structure of the design pattern ................................................................................................................ 19
Configuration 1.1 - Create the object reference using the super class and the creation of the objects using
the subclasses. .................................................................................................................................... 20
Java UML diagram for 1.1 configuration – Variant 1: A reference, an object in memory ........................... 24
Source code for 1.1 Configuration – Variant 1....................................................................................... 25
Explanation of the most relevant lines of code in the 1.1 Configuration – Variant 1 .............................. 27
Java UML diagram for configuration 1.1 - variant 2: Many references, an object in memory by reference 34
Source code for configuration 1.1 - variant 2 ........................................................................................ 35
Explanation of the most relevant lines of code in configuration 1.1 - variant 2 ...................................... 36
Configuration 1.2 - References of objects and objects are created using the subclasses ........................... 38
Utility of configuration 1.2 .................................................................................................................... 39
Java UML diagram for configuration 1.2 ................................................................................................... 41
Código fuente para la configuración 1.2 ............................................................................................... 42
Explanation of the most relevant lines of code in configuration 1.2 ...................................................... 45
Group number two of configurations ........................................................................................................... 55
What happens if subclasses are declared with the abstract class modifier? .............................................. 55
Diagram of Java classes in UML - Configuration 2, possibility 1 (Inherit a pattern) .................................... 58
Source code of configuration 2, possibility 1 (Inherit a pattern) ............................................................ 59
End of chapter I - "How to use abstract classes in class inheritance" ................................................................ 62
Chapter II ......................................................................................................................................................... 65
How to use the classes that are of type Interface in the inheritance relation between classes? .................... 65
Group number three of configurations......................................................................................................... 65
What is an interface? ............................................................................................................................... 65
Example of an interface declaration: ........................................................................................................ 66
Configuration 3.1 - Creating the references of objects using the superclass and the creation of the objects
using the subclasses. ........................................................................................................................... 67
Characteristics of the configuration 3.1 - variant 1: a reference and many objects ................................ 67
Java class diagram in UML for configuration 3.1 - variant 1: a reference and many objects ....................... 68
Source code for configuration 3.1 - variant 1 ........................................................................................ 69
Explanation of the most relevant lines of code, pertaining to configuration 3.1 - variant 1 ................... 72
UML diagram in Java for configuration 3.1 - variant 2: many references and one object by reference ...... 79
Characteristics of the configuration 3.1 - variant 2: many references and one object by reference ....... 80
Source code for configuration 3.1 - variant 2 ........................................................................................ 80
Configuration 3.2 - Create references to objects and objects using subclasses.......................................... 82
Configuration utility 3.2 ........................................................................................................................... 82
How to implement the algorithms that are static? ................................................................................... 82
How to implement algorithms that are dynamic? ..................................................................................... 82
What is the static assignment of the reference? ....................................................................................... 82
What is the dynamic assignment of the reference? .................................................................................. 83
Class diagram in Java for configuration 3.2 - variant 1 .............................................................................. 84
Class diagram in Java for configuration 3.2 - variant 2 .............................................................................. 89
Source code for configuration 3.2 - variant 2 ........................................................................................ 90
Chapter III ........................................................................................................................................................ 93
Polymorphic algorithms that are mutable .................................................................................................... 93
What are mutable polymorphic algorithms? ................................................................................................ 93
What are mutable methods? ....................................................................................................................... 93
Class diagram for polymorphic algorithms that are mutable. Combination 1 - variant 1............................ 95
Source code that implements mutable polymorphic algorithms. Combination 1 - variant 1 ...................... 96
Class diagram in UML for mutable polymorphic algorithms. Combination 2 - variant 1 ........................... 100
Source code that implements mutable polymorphic algorithms. Combination 2, variant 1 ..................... 101
Chapter IV ..................................................................................................................................................... 105
Programming a computer game ................................................................................................................. 105
Polymorphic code of the game ............................................................................................................... 105
View of the computer game: Fly to the end................................................................................................ 106
Class diagram in Java for the Game: Fly to the end ..................................................................................... 107
Structure of folders and packages for the source code in Java .................................................................... 110
Source code in Java for the game view module .......................................................................................... 111
Source code for the classes that implement the client module ................................................................... 114
Source code for classes that implement the specialized behavior provider................................................. 118
Farewell words .............................................................................................................................................. 130
POLYMORPHISM IN JAVA
Chapter I
Introduction
In the construction of a software product, different structures are defined that determine the
architecture of the software that will be built. The basic structures in Java are the classes and the
relationships between the classes. Many times, a structure forms a recurring pattern in the
construction of a software product. A programmer attentive to identifying structures and patterns
can define an appropriate architecture to solve problems or build software. A proper architecture
is as important as the development process in software engineering.
A layer structure can determine an appropriate architecture to define specific functions that are
placed as strata; each layer can be replaced by a new layer without affecting the others. A precise
and unique communications interface must be defined between the layers.
Layer 3 - Polymorphism
Layer 3 is the layer where polymorphic methods and polymorphic algorithms are written. Layer 4
separates the implementation of the polymorphic algorithms from the implementation of the
solution of the problem; the polymorphic algorithms express different ways of using a solution of
a problem.
Página 13 de 130
POLYMORPHISM IN JAVA
Design pattern based on inheritance
Link
Superclass
Subclasses
Abstract methods
Interface
The image shows a generic representation of a design pattern based on the inheritance between
classes. Certain restrictions will configure different design patterns more suitable to be
implemented in Java.
Página 14 de 130
POLYMORPHISM IN JAVA
Layered architecture to use a design pattern
The following image shows an architecture made by layers. Each layer has a certain function to
implement, use and show the solution of a problem.
Link
Static Dynamic
polymorphic polymorphic
methods methods Superclass
Static Dynamic
polymorphic polymorphic Subclasses
algorithms algorithms
• Abstract methods
• Interface
Página 15 de 130
POLYMORPHISM IN JAVA
Description of the design pattern based on the inheritance
The configurations can be divided into three groups, the criteria used to assemble the different
groups of configurations is the declaration of abstract methods and the implementation of abstract
methods by superclasses or subclasses.
What is an interface?
The interface is a totally abstract class; it does not have Java code in its body. The interface declares
prototypes of abstract methods that will be inherited by other classes. Classes that inherit an
interface should overwrite the abstract methods and implement the missing code.
Página 16 de 130
POLYMORPHISM IN JAVA
Programmers usually link the declaration of the reference and the creation of the object in a line of
code. The following line of code is a declaration of a reference to an object and the creation of an
object instance: Rectangulo rectangulo = new Rectangulo(3, 4);
Página 17 de 130
POLYMORPHISM IN JAVA
Structure of the book
Design pattern
Mutable
Polymorphism Polymorphism
polymorphism
Group properties
Create references Create objects
Superclass
Subclass
Interface
Página 18 de 130
POLYMORPHISM IN JAVA
Group number one of configurations
In group number one, there are configurations where the superclass is declared abstract, within this
group there are two configurations. Configuration number one declares the object reference using
the name of the superclass and the creation of the objects using the constructors of the subclasses.
The second configuration creates the reference of objects and objects using the subclasses.
This group has the fundamental characteristic that it prevents to create an object using the
constructor of the superclass. When declaring the superclass as abstract, it is not possible in Java
to create an object of an abstract class. In this group all the objects that can be created must be
created using the constructors of the subclasses.
Group properties
Create references Create objects
Superclass (abstract) Yes Not allowed
Subclass Yes Yes
In group one there are two very interesting configurations that form an adequate architecture to use
the inheritance pattern between classes.
Each configuration of the group includes an additional restriction that forces to make a correct use of
the design pattern.
The design pattern must declare an interface of public methods that can be invoked by the classes
that want to access the pattern. The design pattern is a provider of behaviors.
The design pattern has to be encapsulated in a package and allow or restrict one of the following
four functions, depending on the problem you wish to solve.
In this book we will make a detailed study of the first two functions: 1) declare references of the
subclasses or the superclass, 2) declare objects of the subclasses or the superclass.
The possibilities of extension and changes in the design pattern will be left out of the study, in this
book. A detailed study will be made on the use of the design pattern by other classes. The classes
that will use the design pattern are called "clients."
Classes that are clients of the design pattern may implement polymorphic methods and algorithms.
Página 19 de 130
POLYMORPHISM IN JAVA
Configuration 1.1 - Create the object reference using the super class and the creation of the
objects using the subclasses.
In the configuration 1.1 a new restriction is added, in the new restriction it is not advisable to create
references of the subclasses. In this configuration there are two restrictions: it is not feasible to
create objects of the superclass and it is not recommended to create references of the subclasses.
If there is a reference there may be a specialized object in memory. The only reference works like a
pointer that goes through the objects one by one. To access a new object you have to destroy the
current object and build a new object.
Página 20 de 130
POLYMORPHISM IN JAVA
If you have an object reference that points dynamically to different objects, it can happen that the
use of memory is reduced but the work of the garbage collector Java is very arduous; On the
other hand, when many references to objects are created, the use of memory is more likely to
increase and the work of the garbage collector decreases.
Dynamic assignment of new objects to a single reference causes objects not referenced in memory
to be cleaned by the Java garbage collector.
If the problem to be solved needs to create references to the subclasses, it would be appropriate to
use the 1.2 configuration or another configuration of another group.
The dynamic assignment of the reference to a new object allows the application of the dynamic
polymorphism mechanism, using the unique reference, unique messages can be sent to different
specialized objects.
To apply or use the mechanism of the dynamic polymorphism, it is necessary to send messages to
the objects through the methods interface. Each object must implement the same methods
interface.
The messages are sent to the methods implemented in the objects, if all the objects implement the
same methods interface then it is feasible to send the same message to each object. Each object
will implement a different algorithm and behave differently even if the message sent is the same.
The programmers, are very creative, write algorithms based on objects that send messages.
Algorithms based on sending messages are called polymorphic algorithms. Do not confuse
message-based polymorphic algorithms with specialized algorithms that are implemented in the
objects that receive the messages. Polymorphic algorithms are programmed in clients that use the
class inheritance pattern; the specialized algorithms are programmed in the subclasses or
superclasses of the pattern.
Objects that receive messages from another object implement behavioral algorithms and algorithms
that send messages to another object are called polymorphic algorithms.
From the point of view of the classes we can say that there are classes, clients, that send messages
and classes, servants or suppliers, that respond to messages. The client classes implement
polymorphic algorithms and the supplying classes implement behavioral or specialized
algorithms.
Java classes have three mechanisms to implement interfaces of data access methods or algorithms
that they implement.
1. Inherit an interface: the Java keyword "implements" is used.
2. Declare abstract methods: the Java keyword "abstract" is used.
3. Declare public methods of access to private or encapsulated data.
Página 21 de 130
POLYMORPHISM IN JAVA
Layered Application Organization
Scheme that shows the relationship between: the algorithms that are polymorphic and the algorithms
that have a specialized behavior.
Supplier pattern
Implements behavioral
Client
algorithms
Implements
polymorphic Superclass
algorithms
Interface of abstract
methods
It is advisable to organize the system into at least two layers, one layer for classes that are clients
and another layer for classes that are suppliers.
The same reasoning can be used if the application was designed with three or more layers. The
packets may contain other packets so one layer may contain other layers or sublayers. In Java, a
package is a folder created by the Operating System.
Página 22 de 130
POLYMORPHISM IN JAVA
IDEs, (Integrated Development Environments), are tools that help create applications that will
contain Java code projects. The projects will contain packages and the packages will contain files
with source code written in the Java language.
Página 23 de 130
POLYMORPHISM IN JAVA
Java UML diagram for 1.1 configuration – Variant 1: A reference, an object in memory
Página 24 de 130
POLYMORPHISM IN JAVA
Source code for 1.1 Configuration – Variant 1
package app;
import patron.Figura;
import patron.Rectangulo;
import patron.TrianguloRectangulo;
System.out.println(figura.getClass().getName());
System.out.println(" Altura = " + figura.getAltura());
System.out.println(" Base = " + figura.getBase());
System.out.println(" Área " + figura.area());
System.out.println(" Color " + figura.obtenerColor());
Página 25 de 130
POLYMORPHISM IN JAVA
package patron;
import java.awt.Color;
//Niveles de control de acceso public para clases, una clase pública puede ser
accedida por cualquier clase de cualquier paquete
//Una clase sin modificador puede ser accedida por una clase de su mismo paquete
package patron;
import java.awt.Color;
@Override
public Integer area() {
return this.getAltura() * this.getBase();
}
Página 26 de 130
POLYMORPHISM IN JAVA
@Override
public Color obtenerColor() {
// TODO Implement this method
return color;
}
}
package patron;
import java.awt.Color;
@Override
public Integer area() {
return (this.getAltura() * this.getBase()) / 2;
}
@Override
public Color obtenerColor() {
// TODO Implement this method
return color;
}
Explanation of the most relevant lines of code in the 1.1 Configuration – Variant 1
This line of code indicates that the class Main{} belongs to the package called app, the package
called app will contain the classes of the layer named client.
package app;
Importing the classes from the package called patron. The package named patron will contain
the classes of the layer named proveedor. Unfortunately, the 1.1 configuration must have
access to all classes in the proveedor layer.
import patron.Figura;
import patron.Rectangulo;
import patron.TrianguloRectangulo;
Declaration of the Main{} class, the class named Main{} must be public. The JVM must find the
Main{} class to create a memory instance.
Página 27 de 130
POLYMORPHISM IN JAVA
Declaration of the constructor method called Main(), the Main() method must be public and
homonymous to the Main{} class. The JVM will search and execute the Main() method at the
time of creating an instance of the Main{} class.
Declaration of the constructor method, with the name of Main(). The Main() method must be
public and homonym to the Main{} class. The JVM will search and execute the Main() method
at the time of creating an instance of the Main{} class.
public Main() {
super(); //invoca el constructor de la superclase Object
}
Declaration of the reference to objects with the name of: unaFigura. The unaFigura reference is
of type Figure{}. The unaFigura reference is not pointing to an object instance.
Statement of the main() method, the main() method will be searched and executed by the JVM at
the time of instantiating the Main{} class.
Main main = new Main(); //el objeto main tiene información relevante a
la clase Main{}
This statement will point to the reference named unaFigura to the new object created by the
constructor named Rectangulo().
The following line of code will execute the Polymorphic method called polimorfismo() with the
parameter of type Figura{} and the argument of the type Rectangulo{}.
A method is polymorphic when the JVM must decide which method to execute depending on the
type of parameter and the argument type. The JDK cannot predict at design time which method to
run because it does not know the argument type of the parameter.
polimorfismo(unaFigura);
The reference, called unaFigura, is pointed to a new object created by the constructor named
TrianguloRectangulo(). The rectangle object does not have a valid reference and must be
cleaned by the garbage collector. A reference is polymorphic if it is feasible to change the
referenced object type.
Página 28 de 130
POLYMORPHISM IN JAVA
unaFigura = new TrianguloRectangulo(6, 8);
The following line of code executes the polymorphic method called polimorfismo(), the method
has the parameter of type Figura{} and the argument of the parameter of type
TrianguloRectángulo{}.
polimorfismo(unaFigura);
The following code declares the dynamic polymorphic method called polimorfismo(), the
dynamic polymorphic methods are characterized by having the parameters of a type and the
arguments can be of another type. The parameter is of type Figure{} and the arguments can be
of the type Rectangulo{} and TrianguloRectangulo{}. The dynamic polymorphic
methods have polymorphic algorithms; the polymorphic algorithms are characterized by having
different behaviors depending on the argument assigned to the parameter. Dynamic polymorphic
methods send messages and are received by the classes that are providers of the different
behaviors. The classes that are clients implement polymorphic algorithms and the classes that are
providers implement specialized behavior algorithms. The main feature of dynamic polymorphic
algorithms is that they change their behavior depending on the argument assigned to the
parameter.
Summary of Concepts:
• A method is polymorphic if it is overloaded in its parameters or arguments or both.
• An algorithm is polymorphic if it always sends the same message to classes that are
providers of behaviors. The class, client, Main{} sends messages getAltura(),
getBase(), area() y getColor() to classes that are providers of such behaviors.
• Classes that are customers implement polymorphic methods and algorithms, polymorphic
methods, and polymorphic algorithms send messages to classes that are providers of
specialized behaviors.
Página 29 de 130
POLYMORPHISM IN JAVA
The classes that are providers implement a single method interface to receive messages from the
classes that are clients.
This line of code indicates that the class named Figura{} belongs to the package named patron,
the package with the patron name will contain the classes of the layer named proveedor.
package patron;
Statement to import the class named Color from the package named java.awt.
import java.awt.Color;
Class declaration with the name of Figura{}, the class named Figura{} must be public because it
is invoked from the app package.
Declaration of the constructor method called Figura(), the constructor method named Figura()
must be public and homonymous to the class named Figura{}. The constructor is invoked at the
time of creating an object instance. It is a good idea to use the constructor method to initialize the
fields of the class. The constructor method is the primary interface for accessing private data in
the class at the time of constructing an object. Constructor methods can be overloaded in their
parameters and arguments.
The following statements are the interface of public methods to access private data.
Página 30 de 130
POLYMORPHISM IN JAVA
}
In a method declaration, the overload of parameters and arguments is the mechanism that guarantees
the construction of polymorphic algorithms.
This line of code indicates that the class named Rectangulo{} belongs to the package named
patron, the package named patron will contain the classes of the layer named proveedor.
package patron;
import java.awt.Color;
Declaration of a class with the name Rectangulo{}. The class called Rectangulo{} must be
public since it is invoked from the package called app. It also extends new functions and inherits
the interface of public methods of access to private data declared in the inherited class.
Página 31 de 130
POLYMORPHISM IN JAVA
private Color color = new Color(0, 0, 0);
The methods that are constructors have access to the data structure of the inherited class; it is a good
idea to initialize the data of the superclass when creating an instance of a subclass.
The following lines of code overwrite, @Override, the legacy abstract methods. The methods that
are declared abstract do not have code implemented; it is the subclass obligation to implement the
missing code.
@Override
public Integer area() {
return this.getAltura() * this.getBase();
}
@Override
public Color obtenerColor() {
// TODO Implement this method
return color;
}
It is not necessary to comment on the following code since it has been commented previously.
package patron;
import java.awt.Color;
@Override
public Integer area() {
return (this.getAltura() * this.getBase()) / 2;
}
@Override
public Color obtenerColor() {
// TODO Implement this method
return color;
}
Página 32 de 130
POLYMORPHISM IN JAVA
Summary of the hierarchical structure of classes
The classes that are clients send messages to the subclasses; the subclasses manage the algorithms
implemented in their own body and the algorithms implemented in the superclass through
inheritance. The superclass forces the subclass to implement certain methods.
Messages
Abstract
Client Subclasses superclass
Messages
Implement
Abstraction process: The process of abstraction lies in determining the data structure and the
hierarchical structure of classes that solve a problem. Given a hierarchical class structure,
attentive programmers can ask: Can it contain different algorithms to solve problems?
Página 33 de 130
POLYMORPHISM IN JAVA
Java UML diagram for configuration 1.1 - variant 2: Many references, an object in memory by
reference
Página 34 de 130
POLYMORPHISM IN JAVA
Source code for configuration 1.1 - variant 2
package app;
import patron.Figura;
import patron.Rectangulo;
import patron.TrianguloRectangulo;
Página 35 de 130
POLYMORPHISM IN JAVA
//La JVM Java decide que comportamiento ejecutar dependiendo del
tipo del argumento enviado en el parámetro
System.out.println(figura.getClass().getName());
System.out.println(" Altura = " + figura.getAltura());
System.out.println(" Base = " + figura.getBase());
System.out.println(" Área " + figura.area());
System.out.println(" Color " + figura.obtenerColor());
The configuration 1.1 in variant 1, declares a reference and an object instance, the only reference is
pointed to a new object instance whenever it is needed. The memory usage is small but the JVM
must collect instances of non-referenced objects.
The configuration 1.1 in variant 2, declares many references and an object instance for each
reference, each reference is pointed to an object instance. The use of memory is greater because
of the large number of objects in memory. The JVM has little work, since it should not collect
unreferenced objects.
Note: In configuration 1.1 variant 2, the modifications of the source code have been made in the
class that has the client role. The classes that have the role of suppliers have not had changes in
the code and have remained the same as the configuration 1.1 variant 1.
Only the source code of the class with the client role will be explained: Main{}. The rest of the
source code is identical to the configuration 1.1 variant 1.
Página 36 de 130
POLYMORPHISM IN JAVA
package app;
import patron.Figura;
import patron.Rectangulo;
import patron.TrianguloRectangulo;
In variant number two, you must create the same number of references of objects and instances of
objects to solve the problem.
For each reference you have to create an object instance, there are as many objects as references
have been created. If the JVM finds an unreferenced object, it will clear it from memory. Variant
number two tries to reduce the work of the JVM by keeping all the objects with their
corresponding reference throughout the execution of the application.
Página 37 de 130
POLYMORPHISM IN JAVA
The JVM will evaluate the method argument at run time: private static void
polimorfismo(Figura figura) {…}, to decide which method to execute given the object
instance called figura, for example: figura.getAltura();
The polymorphism mechanism allows to reduce the code written by the programmers and create
reusable modules. An astute programmer will always find a way to write little code and let the
JVM have to do as much work as possible when solving a problem.
Configuration 1.2 - References of objects and objects are created using the subclasses
In configuration 1.2, a new constraint is established, it is not feasible to create references from the
superclass. In this configuration there are two restrictions: do not create objects of the superclass
and do not create references of the superclass.
Página 38 de 130
POLYMORPHISM IN JAVA
In configuration 1.2, references and objects are created from subclasses.
It is a suitable configuration for when there are few specialized objects, each object has the need to
implement a particular or unique algorithm. If so many references are declared as specialized
objects it is possible to have in memory all the objects that are needed to solve a problem. Each
reference works as a pointer to each specialized object. Objects can remain in memory during the
entire execution time of the application.
A static assignment means that the reference and the object instance are made with the same class.
The compiler can easily deduce, at design time, the type of object declared in a parameter of a
method. In a static assignment the parameter and the arguments are of the same type.
The static assignment of each reference to an object allows applying the static polymorphism
mechanism, each reference can send messages to a specialized object. If all subclasses implement
a single interface, they can receive identical messages from the references.
To apply or use the static polymorphism mechanism you need to send messages to the objects
through a method interface. Each object must implement the same methods interface.
The declaration of abstract methods in the superclass specifies a contract that subclasses must
respect. Subclasses will comply with the contract when they implement the missing code. The
declaration of non-abstract methods in the superclass specifies an optional contract that
subclasses could meet or not comply with.
Página 39 de 130
POLYMORPHISM IN JAVA
The methods declared as abstract are widely used by systems analysts to specify user requirements
during the process of building a software product.
The process of abstraction is a psychological process that a human performs to find the solution to a
problem. Classes and abstract methods are tools that information systems analysts use to specify
the solution to a problem. The programmers interpret the specifications indicated by the
information systems analysts and write the missing or specified code.
Página 40 de 130
POLYMORPHISM IN JAVA
Java UML diagram for configuration 1.2
Página 41 de 130
POLYMORPHISM IN JAVA
Código fuente para la configuración 1.2
package app;
import patron.Rectangulo;
import patron.TrianguloRectangulo;
public class Main {
public Main() {
super();
}
private static Rectangulo rectangulo = null;
private static TrianguloRectangulo trianguloRectangulo = null;
}
//El compilador Java decide que método ejecutar en tiempo de ejecución
//Método polimórfico o sobrecargado por el parámetro
private static void polimorfismo(Rectangulo figura) {
//Líneas no polimórficas, siempre se comportan como un rectángulo
//El compilador Java decide que comportamiento ejecutar en tiempo de
diseño
System.out.println(figura.getClass().getName());
System.out.println(" Altura = " + figura.getAltura());
System.out.println(" Base = " + figura.getBase());
System.out.println(" Área " + figura.area());
System.out.println(" Color " + figura.getColor());
}
System.out.println(figura.getClass().getName());
System.out.println(" Altura = " + figura.getAltura());
Página 42 de 130
POLYMORPHISM IN JAVA
System.out.println(" Base = " + figura.getBase());
System.out.println(" Área " + figura.area());
System.out.println(" Color " + figura.getColor());
}
}
package patron;
import java.awt.Color;
public final class Rectangulo extends Figura {
private Color color = new Color(0, 0, 0);
public void setColor(Color color) {
this.color = color;
}
package patron;
import java.awt.Color;
public final class TrianguloRectangulo extends Figura {
private Color color = new Color(0, 0, 0);
public void setColor(Color color) {
this.color = color;
}
public Color getColor() {
return color;
}
public TrianguloRectangulo(Integer b, Integer a) {
super(b, a);
color = Color.green;
}
@Override
public Integer area() {
return (this.getAltura() * this.getBase()) / 2;
Página 43 de 130
POLYMORPHISM IN JAVA
}
@Override
public Integer getAltura() {
// TODO Implement this method
return super.getAltura();
}
@Override
public Integer getBase() {
// TODO Implement this method
return super.getBase();
}
}
package patron;
Página 44 de 130
POLYMORPHISM IN JAVA
Explanation of the most relevant lines of code in configuration 1.2
Comments will be made on the most interesting aspects of the lines of code; many lines of code
have been discussed above.
package app;
The following lines of code import the classes from the package called patron. The package called
patron will contain the classes of the layer called proveedor. An interesting aspect of the 1.2
configuration is that it is not necessary to access the class called Figura{}. The class with the
name of Figura{} must be encapsulated in the package called patron. To encapsulate a class
in a package, you must use the default modifier in the declaration of the name of the class.
import patron.Rectangulo;
import patron.TrianguloRectangulo;
These lines of code are the declaration of the references to the subclasses, the references are not
pointing to any object. The configuration 1.2 does not need to access the class Figura{}, for
this reason, the class Figure{} has been declared non-public in the proveedor layer.
Execution of the static polymorphic method called polymorphism (). The parameter and the
argument are of the same type, in this case it is of the rectangle type.
polimorfismo(rectangulo);
Execution of the static polymorphic method called polymorphism (). The parameter and the
argument are of the same type; in this case it is of the right triangle type.
Página 45 de 130
POLYMORPHISM IN JAVA
polimorfismo(trianguloRectangulo);
The following code implements the declaration of the two static polymorphic methods necessary to
solve the area calculation problem. The two methods have the same name: polymorphism (...).
The two methods are differentiated by the type of parameter.
Static polymorphic methods are characterized by having parameters and arguments of the same type.
The parameter and the argument are of the type: 1) rectangle, 2) right triangle.
Static polymorphic methods send messages to classes that have the role of providing the desired
behaviors. Classes that are clients implement static polymorphic algorithms. The classes that are
providers implement specialized behavior algorithms.
The main characteristic of static polymorphic algorithms is that the behavior and messages sent are
defined at the design time of the Java application.
System.out.println(figura.getClass().getName());
System.out.println(" Altura = " + figura.getAltura());
System.out.println(" Base = " + figura.getBase());
System.out.println(" Área " + figura.area());
System.out.println(" Color " + figura.getColor());
Página 46 de 130
POLYMORPHISM IN JAVA
//El compilador Java decide que método ejecutar en tiempo de diseño
según su parámetro
//Método polimórfico o sobrecargado por el parámetro.
System.out.println(figura.getClass().getName());
System.out.println(" Altura = " + figura.getAltura());
System.out.println(" Base = " + figura.getBase());
System.out.println(" Área " + figura.area());
System.out.println(" Color " + figura.getColor());
Summary of concepts:
• A method is polymorphic if it is overloaded in its parameters or arguments or both.
• An algorithm is polymorphic if it sends the same message to the classes supplying the
specialized behaviors. In this case, the class with the client role sends the getAltura(),
getBase(), area() and getColor() messages to the supplying classes of these
behaviors.
• Classes that are clients implement polymorphic methods and algorithms. Polymorphic
algorithms send messages to classes that provide specialized behavior.
• The classes that have the role of providers implement a single methods interface to receive
messages from the classes that have the role of clients.
The following classes belong to the package with the name of "patron". These classes will provide
specific behaviors.
Many of these lines of code have already been commented, the most relevant aspects will be
discussed.
package patron;
The following lines of code declare the class called Figura{}, the class called Figura{} is
declared without the access modifier, the default access modifier indicates that the class is
protected in the package that contains it.
Página 47 de 130
POLYMORPHISM IN JAVA
4. without modifier: the field that has the default modifier is accessed by the classes that belong
to the same package (only when necessary)
The following code is the declaration of the constructor method called Figura(), the method called
Figura() must be public and homonymous to the class called Figura{}. It is a good idea to
use the constructor method to initialize the fields in the class. The constructor method is the
primary interface for accessing the private data of the class. If a class is abstract its constructor
method can be invoked by the class that inherits it.
The following lines of codes are the declaration of the interface of private data access methods of
the class. If a method is declared without a modifier, only the classes of its same package can
access the method. The methods can have four modifiers:
Página 48 de 130
POLYMORPHISM IN JAVA
1. without modifier: only the classes in the same package access the method
2. protected: only the classes of the same package access the method and the classes that
inherit the method, the classes that inherit the method can be in another package
3. public: all classes can access the method
4. private: no class can access the method, only the class itself can access the method
integer getAltura() {
return altura;
}
integer getBase() {
return base;
}
The next line of code is the declaration of the interface of abstract methods, there will be as many
methods called area () as there are subclasses. Abstract methods must be overwritten by the class
that inherits this class. If a method is declared without the access modifier, then only the classes
in the same package can access the method.
Important note and a fascinating detail about polymorphism in Java: You have to understand that
a line of code has been written, and it is correct to say: "interface of abstract methods". In the
future, the classes that have the role of clients will be able to create many objects of different
types, each type of object will implement a different version of the method called area().
This line of code indicates that the class Rectangulo{} belongs to the package called patron, the
package with the name of patron will contain the classes of the layer called proveedor.
package patron;
import java.awt.Color;
The following line of code is the declaration of the class called Rectangulo{}, it is a public class
since it will be invoked from the package with the name of app. The Rectangulo{} class is
extended from the class called Figura{} and inherits the public methods interface to access the
private data of the Figura{} class. The final modifier indicates that the class
Rectangulo{} can not be inherited by another class, programmers must necessarily instantiate
an object of the class Rectangulo{}.
Página 49 de 130
POLYMORPHISM IN JAVA
The following lines of code overwrite the abstract methods inherited from the superclass. The
method that is overwritten will implement the specialized or more specific code than the code
implemented in the superclass. Each subclass will implement a more specialized or more specific
code version. Normally, superclasses implement a code of a higher level of abstraction, and
subclasses implement a code of a greater level of concretion or specialization. It is also advisable
to implement in the superclass the code that all subclasses need. If there is a subclass that needs
exclusive code, it would be better if those classes take over the exclusive code. When subclasses
need to implement a unique code, the superclass will declare a method with the abstract modifier.
If subclasses need to execute shared code, then the superclass will implement methods with code
in its body.
@Override
public Integer area() {
//implementar el código faltante en la superclase
//implementación del código especializado o de mayor concreción
return this.getAltura() * this.getBase();
@Override
public Integer getAltura() {
// TODO Implement this method
//ejecutar el código de mayor abstracción, implementado en la
superclase
return super.getAltura();
}
@Override
public Integer getBase() {
// TODO Implement this method
//ejecutar el código de mayor abstracción, implementado en la
superclase
return super.getBase();
Página 50 de 130
POLYMORPHISM IN JAVA
}
Example of abstraction in the superclass: all the figures have sides, the quadrilaterals and the
triangles that are rectangles have in common the base and the height.
With respect to the color property of the figures, it is the responsibility of the analysts to decide if
the color property will be implemented in the superclass or implemented in the subclasses. The
process of abstraction is the task of deciding how the properties of the problem to be solved will
be grouped. It will always be the responsibility of analysts and programmers to decide what level
of abstraction a property of an object will have.
During the development process in the construction of a software product, analysts and
programmers participate in the solution of a problem by separating or grouping the properties and
procedures that give solution to the proposed problem.
The class hierarchy is a construction that helps to separate and group the properties and procedures
that define the objects that participate in the solution of a problem. In a hierarchy of classes
related by inheritance, the classes that have the role of being superclasses will implement the
general or more abstract aspects of the problem to be solved. And the classes that have the role of
being subclasses will implement the particular or more concrete aspects of the proposed solution.
Página 51 de 130
POLYMORPHISM IN JAVA
Solution
Less Higher
Subclasses
Abstraction
Concretion
Superclass
Issue
Higher Less
Página 52 de 130
POLYMORPHISM IN JAVA
The following graph shows the relationship between the design pattern and polymorphic algorithms
Client
Polymorphic algorithms
Subclasses
Abstraction
Concretion
Superclass
Issue
Higher Less
Note and detail to keep in mind: Some problems have solutions with a higher level of abstraction,
for example: scientists who study distant galaxies look for general solutions that explain the
cosmological processes.
Página 53 de 130
POLYMORPHISM IN JAVA
The following lines of code implement a class with the name of: TrianguloRectangulo{}, the
class belongs to the package called patron. The package called patron will contain the classes
of the layer called the proveedor.
This class will implement the highest level of concretion for triangles that are rectangles. Details of
higher abstraction level will be inherited from the class called Figura{}. It will also implement
a public methods interface to offer the services that customers require. And will specialize in the
calculation of triangles that are rectangles, customers will request these services by sending
messages.
package patron;
import java.awt.Color;
@Override
public Integer area() {
return (this.getAltura() * this.getBase()) / 2;
}
@Override
public Integer getAltura() {
// TODO Implement this method
return super.getAltura();
}
@Override
public Integer getBase() {
// TODO Implement this method
return super.getBase();
}
Página 54 de 130
POLYMORPHISM IN JAVA
Group number two of configurations
In the group of configurations number two, the subclasses are declared with the modifier:
abstract. The configuration of subclasses declared as abstract is not recommended. Surely
some particular problems need this type of configuration.
In group two there are two possibilities to use the design pattern:
Possibility 1: inherit the abstract subclasses of the design pattern (recommended)
Possibility 2: declare references to instances of objects and instances of objects using the
superclass (not recommended)
In possibility number two: it is not possible to apply the polymorphism mechanism; it is not feasible
to differentiate the types of objects.
Declaring subclasses as abstract classes is an exceptional situation and will largely depend on the
problem to be solved. It is advisable to try, in a first instance, to declare the superclass with the
abstract class modifier.
What happens if subclasses are declared with the abstract class modifier?
When declaring a subclass with the abstract class modifier, a very large constraint is imposed and
the Java compiler will give errors every time an object of an abstract subclass is built. Remember
that it is not feasible to instantiate objects from an abstract class.
Properties of configuration 2
Create Create
references objects
Superclass Yes Yes It does not have much use
Subclass Not Compiler error
Yes
(abstract) allowed (Inherit the design pattern to skip the errors)
Classes that have the customer role of the design pattern can not use the design pattern effectively. It
is advisable that the classes that have the customer role of the design pattern inherit the design
pattern.
Many of the following lines of Java code would generate compiler errors at design time.
package app;
import patron.Figura;
import patron.Rectangulo;
import patron.TrianguloRectangulo;
Página 55 de 130
POLYMORPHISM IN JAVA
public Main() {
super();
}
//////////////////////////////////////
//Esto no es un error
//No tiene mucha utilidad crear referencias y objetos de una superclase
figura = new Figura();
//////////////////////////////////////
//Error de tipos: no se puede crear referencias de una subclase y
objetos de una superclase
//Siempre la referencia y el objeto construido deben ser del mismo tipo
rectangulo = new Figura();
//////////////////////////////////////
//Error de tipos: no se puede crear referencias de una subclase y
objetos de una superclase
//Siempre la referencia y el objeto construido deben ser del mismo tipo
trianguloRectangulo = new Figura();
}
}
Página 56 de 130
POLYMORPHISM IN JAVA
Solution to the problems presented by the subclasses that are declared as abstract
The solution is to inherit the subclasses of the design pattern from the classes that have the customer
role. Classes that have the role of client must inherit the design pattern.
The following Java class diagram and the Java code associated with that diagram show how to
inherit a design pattern. The code will not be commented, it was commented in the previous
examples. It is recommended that the programmer write the code in their favorite IDE.
The secret lies in understanding that two new classes have been created that serve as a bridge
between the class that is the client and the design pattern.
Página 57 de 130
POLYMORPHISM IN JAVA
Diagram of Java classes in UML - Configuration 2, possibility 1 (Inherit a pattern)
Página 58 de 130
POLYMORPHISM IN JAVA
Source code of configuration 2, possibility 1 (Inherit a pattern)
package app;
import java.awt.Color;
import patron.Figura;
public Main() {
super();
}
Página 59 de 130
POLYMORPHISM IN JAVA
}
package app;
import java.awt.Color;
import patron.Rectangulo;
package app;
import java.awt.Color;
import patron.TrianguloRectangulo;
Página 60 de 130
POLYMORPHISM IN JAVA
package patron;
import java.awt.Color;
package patron;
import java.awt.Color;
Página 61 de 130
POLYMORPHISM IN JAVA
@Override
public int getArea() {
// TODO Implement this method
package patron;
import java.awt.Color;
The declarations of abstract methods in the superclasses are contracts that the subclasses must
respect and implement in Java code. When a superclass declares abstract methods the subclasses
are forced to overwrite and implement the abstract methods.
What happens if a subclass waives the contract and does not overwrite the abstract methods?
The subclass can not resign, it must over write the abstract methods.
What happens if a subclass overwrites the abstract method, but waives the implementation of the
missing code?
Yes, the subclass can resign. The missing code will be waiting for another class to implement it.
Página 62 de 130
POLYMORPHISM IN JAVA
The topic of classes that are interfaces will be discussed in Chapter II.
This is an example where a method has been overwritten in the creation of an object instance:
unaFigura = new Rectangulo(6, 8){
@Override
public Integer area() {
// TODO Implement this method
//return super.area(); //renunciar al código de la
subclase
//Implementar nuevo código
return this.getAltura() * this.getBase();
}
};
It will always involve specializing or raising the level of concreteness of a solution to a problem
posed. It is optional to write or not write Java code in the body of an overwritten method.
If the method is declared as abstract: the implementation of Java code will be left for later in
the development of a software product.
If the method is not abstract: The code implemented in the body of the method will be a new
version of existing code.
Overwriting a method will involve changes in:
• The answer
• The behavior
The importance of declaring the methods with the public access modifier: public
Overwriting public methods is an appropriate form of communication between classes that form
inheritance trees. Message submissions are used to traverse hierarchical trees. The act of
overwriting public methods is a way of relating classes by sending messages. The name of the
method is the message; the arguments of the parameters are the content of the message. The
responses of the message are the "return" of the method, and the algorithm implemented in the
body of the method is the expected behavior. The expected behavior depends on the algorithm
and the arguments of the parameters. By definition, the polymorphism is to achieve different
behaviors, depending on the arguments of the parameter.
Página 63 de 130
POLYMORPHISM IN JAVA
If the mechanism of the polymorphism has been applied correctly, then the implemented code has
been reused. The reuse of code is one of the objectives of object-oriented programming.
Classes that intend to receive messages must declare public methods; classes that implement public
methods can receive messages and execute an algorithm depending on the content sent in the
arguments of the parameter. To send a message it is necessary to instantiate an object of a class
that has declared a structure of a message.
The importance of the methods that are overwritten: When a class overwrites the methods of another
class, it is trying to communicate with it to send messages and get an answer. The way to replace
the response of a message is to overwrite the message and implement a new algorithm.
If a class is declared abstract, it must necessarily be inherited by another class in order to have the
possibility of overwriting its abstract methods.
Methods that were not declared as abstract can also be overwritten using the @Override tag, it is
not mandatory to overwrite non-abstract methods.
Página 64 de 130
POLYMORPHISM IN JAVA
Chapter II
How to use the classes that are of type Interface in the inheritance relation
between classes?
In the group number three of configurations the superclasses implement the interface with
prototypes of abstract methods, within this group there are two configurations. The number one
configuration creates the object references using the superclasses and the creation of the objects
using the subclasses. The second configuration creates the references of objects and objects using
the subclasses.
This group has no restrictions, it is feasible to create references to objects and create objects using
the constructors of the subclasses and superclass indistinctly.
The use of abstract classes have many restrictions compared to the use of interfaces, the use of
interfaces allow greater flexibility when using the design pattern by the classes that have the role
of clients.
The configurations of this group form an adequate architecture to build a design pattern based on the
inheritance relationship between classes.
1. Configuration 3.1: references are declared using superclasses. And the objects are declared
using the subclasses.
2. Configuration 3.2: references and objects are declared using the subclasses.
What is an interface?
An interface is a special class that has all its methods declared as abstract. You can also declare, in
the body of the interface, the fields that will be constant.
The interfaces are used during the analysis phase in the development of a software product. The
classes that implement these interfaces write the logic of the behavior of the abstract methods.
Página 65 de 130
POLYMORPHISM IN JAVA
It allows to organize the system in modules.
Establishes composition relationships between software parts. Classes can implement more
than one interface per class.
Classes that implement one or more interfaces are obliged to overwrite all the methods declared in
the interfaces.
The following image shows the process of abstraction of the solution of a problem.
Página 66 de 130
POLYMORPHISM IN JAVA
Analysts love the declarations of the interfaces, later the designers and the programmers will be
obliged to implement the modules defined by the information systems analysts.
The interfaces are the highest level of abstraction possible in the process of building a software
product, since they can specify the requirements of users. The eduction of user requirements is
the first task to be performed. The designers and programmers should specify, later, the
algorithms that solve the problems raised.
Configuration 3.1 - Creating the references of objects using the superclass and the creation of
the objects using the subclasses.
In configuration 3.1, two constraints are introduced that force the architecture to function properly
and also make good use of the design pattern based on inheritance between classes.
Characteristics:
A reference
Many objects but only one object in memory
Dynamic assignment of the reference to new objects
Little memory consumption
The JVM garbage collector has a lot of work cleaning the non-referenced objects
Página 67 de 130
POLYMORPHISM IN JAVA
Java class diagram in UML for configuration 3.1 - variant 1: a reference and many objects
Página 68 de 130
POLYMORPHISM IN JAVA
Source code for configuration 3.1 - variant 1
package app;
import patron.Figura;
import patron.Rectangulo;
import patron.TrianguloRectangulo;
System.out.println(figura.getClass().getName());
if(figura.area()>10)
System.out.println(" Color = " + figura.getColor());
System.out.println(" Altura = " + figura.getAltura());
System.out.println(" Base = " + figura.getBase());
System.out.println(" Área = " + figura.area());
}
}
private static void polimorfismo(TrianguloRectangulo figura) {
//acceder a los métodos de TrianguloRectangulo{}, si es necesario
Página 69 de 130
POLYMORPHISM IN JAVA
}
package patron;
package patron;
import java.awt.Color;
@Override
public Integer area() {
Página 70 de 130
POLYMORPHISM IN JAVA
if(this.getClass().getName().equalsIgnoreCase(Rectangulo.class.getName())
) {
package patron;
import java.awt.Color;
///////////////////////
//sobrescribir todos los métodos de la clase Figura{} si es necesario
//////////////////////
@Override
public Color getColor() {
// TODO Implement this method
return super.getColor();
}
@Override
public Integer area() {
// TODO Implement this method
//Opción 1: La clase Rectangulo{} implementa su propio
// algoritmo del cálculo del área
//return super.getAltura() * super.getBase();
package patron;
import java.awt.Color;
Página 71 de 130
POLYMORPHISM IN JAVA
public class TrianguloRectangulo extends Figura {
///////////////////////
//sobrescribir todos los métodos de Figura si es necesario
//////////////////////
@Override
public Color getColor() {
// TODO Implement this method
return super.getColor();
}
@Override
public Integer area() {
Explanation of the most relevant lines of code, pertaining to configuration 3.1 - variant 1
package app;
import patron.Figura;
import patron.Rectangulo;
import patron.TrianguloRectangulo;
Declaration of the reference called figura. This reference is created using the superclass called
Figura{} and will point to an object instance created by the subclass: Rectangulo{} or
TrianguloRectangulo{}.
public Main() {
super();
}
Página 72 de 130
POLYMORPHISM IN JAVA
public static void main(String[] args) {
The next line of code will create a new object using the constructor named Rectangulo().
figura = new Rectangulo(3, 4);
The following code will execute the polymorphic method called polimorfismo(¿…?). The
parameter of the method is of the figure type. And the argument is of the rectangle type. The
assignment of the type in the argument at runtime is known as dynamic polymorphism.
polimorfismo(figura);
The reference called figure is pointed to a new object. The new object is created by the constructor
called TrianguloRectangulo(). The object of type rectangle no longer has a valid
referencing. The garbage collector of the JVM should clean the non-referenced objects.
The following code will execute the polymorphic method called polimorfismo(¿...?). The
parameter of the method is of the figure type. And the argument is of the type of triangles that are
rectangles. The assignment of the type in the argument at runtime is known as dynamic
polymorphism. Any line of Java code that uses a polymorphic reference will be, by extension, a
polymorphic code.
polimorfismo(figura);
}
The following code is the declaration of the polymorphic method called polimorfismo(), the
dynamic polymorphic methods are characterized by having parameters of one type and the
arguments of another type. The parameter is of the figure type and the arguments can be of the
rectangle type and the triangle-rectangle type. Dynamic polymorphic methods have polymorphic
algorithms; polymorphic algorithms are characterized by invoking different behaviors depending
on the argument of the parameter. Dynamic polymorphic methods send messages to classes that
have the role of behavior providers. The classes that have the role of clients implement
polymorphic algorithms and the classes that have the role of providers implement specialized
behavior algorithms. The main characteristic of dynamic polymorphic algorithms is that their
behavior and the sending of messages are defined at runtime.
Página 73 de 130
POLYMORPHISM IN JAVA
System.out.println(figura.getClass().getName());
if(figura.area()>10)
System.out.println(" Color = " + figura.getColor());
The following code is correct and demonstrates that it is feasible to overload the parameter of the
method called polimorfismo() with two different types of arguments.
}
private static void polimorfismo(TrianguloRectangulo figura) {
//acceder a los métodos de TrianguloRectangulo{}, si es necesario
Important notes:
Polymorphic methods and polymorphic algorithms should be implemented in classes that are clients
of a design pattern.
The specialized algorithms should be implemented in the design pattern, the design pattern is built
by the classes that are related through inheritance.
Classes that have the role of clients benefit from implementing algorithms based on sending
messages, reducing their code and reusing lines of code.
The design pattern will decide which specialized algorithm will execute depending on the
parameters and arguments of the received message.
package patron;
import java.awt.Color;
The following code is the declaration of the superclass named Figura{}, the superclass will
implement an interface named CalcularArea{}.
The following methods are the public interface to access the private fields of the Figura{} class.
Página 74 de 130
POLYMORPHISM IN JAVA
The following code is the declaration that overwrites the abstract method called area(), the
abstract method was declared in the interface named CalcularArea{}, the overriding method
can implement the specialized algorithms for each subclass. If the subclasses are many, the
superclass named Figura{} can give up writing specialized Java code and allow each subclass
to implement its own algorithms. Normally subclasses are responsible for overwriting methods
that are abstract and implement algorithms with a greater level of detail.
The programmers can decide to write the specialized algorithms in the subclasses or in the
superclass, it is recommended to write the specialized code in the subclasses.
To execute Java code implemented in a superclass, subclasses can use the following Java keywords:
super and this.
To execute Java code implemented in a subclass or in a superclass, the classes that have the client
role will use the following options:
Analysis of the type of object by the JVM, in execution time. (dynamic polymorphism)
Analysis of the type of object by the JDK, at design time. (static polymorphism)
.
@Override
public Integer area() {
if(this.getClass().getName().equalsIgnoreCase(Rectangulo.class.getName())) {
return altura * base;
}else{
return (altura * base) / 2;
}
Página 75 de 130
POLYMORPHISM IN JAVA
The following code is the declaration of the subclass named Rectangulo{}. The subclass has
inherited members of the superclass named Figura{}.
The subclass overwrites the abstract method, for the second time, called area(). The abstract
method was implemented in the superclass Figura{}, the class Rectangulo{} has the
opportunity to implement its own algorithm or invoke the algorithm already implemented in the
class Figura{}.
package patron;
import java.awt.Color;
///////////////////////
//sobrescribir todos los métodos de la clase Figura{}, si es necesario
//////////////////////
@Override
public Color getColor() {
// TODO Implement this method
return super.getColor();
}
@Override
public Integer area() {
Página 76 de 130
POLYMORPHISM IN JAVA
La clase TrianguloRectangulo{} sobrescribe el método area() implementado en la clase
Figura{}, la clase TrianguloRectangulo{} tiene la oportunidad de implementar su propio
algoritmo o invocar al algoritmo ya implementado en la clase Figura{}.
Los programadores pueden decidir escribir algoritmos especializados en las subclases o en la
superclase, depende de las decisiones de los programadores o del problema que se quiera
resolver.
The following code is the declaration of the subclass named TrianguloRectangulo{}. The
subclass has inherited members of the superclass named Figura{}.
The subclass overwrites the abstract method, for the second time, called area(). The abstract
method was implemented in the superclass Figura{}, the class TrianguloRectangulo{} has
the opportunity to implement its own algorithm or invoke the algorithm already implemented in
the class Figura{}.
package patron;
import java.awt.Color;
///////////////////////
//sobrescribir todos los métodos de la clase Figura{}, si es necesario
//////////////////////
@Override
public Color getColor() {
// TODO Implement this method
return super.getColor();
}
@Override
public Integer area() {
Página 77 de 130
POLYMORPHISM IN JAVA
The following lines of code are the declaration of the interface with the name of CalcularArea{},
that interface will declare the prototypes of abstract methods. The following statement: public
Integer area(); it is the declaration of a prototype of an abstract method. Methods that are
abstract have no body to implement Java code.
package patron;
The class that has the superclass role in the inheritance hierarchy is obliged to implement the
abstract method called area(). The interface CalcularArea{} is a contract that the superclass
Figura{} has to fulfill.
The contract declared by the CalcularArea{} interface could have more obligations for the
superclass named Figura{}. For example:
package patron;
Note: In the declaration of the interfaces, it is normally omitted: the use of the static access
modifier and the abstract keyword.
The following code does not omit the use of keywords: static and abstract.
Página 78 de 130
POLYMORPHISM IN JAVA
UML diagram in Java for configuration 3.1 - variant 2: many references and one object by
reference
Página 79 de 130
POLYMORPHISM IN JAVA
Characteristics of the configuration 3.1 - variant 2: many references and one object by reference
In the configuration 3.1 variant 2 two references are created using the superclass Figura{}, these
references have the name of rectangulo and trianguloRectangulo. The references are
pointed, respectively, to two instances of objects. These objects are instantiated using the
constructor methods of the subclasses: Rectangulo{} and TrianguloRectangulo{}
The task or strategy of variant 2, is to create all references and objects at the start of the application
and let them remain in memory for the entire duration of the execution of the application.
Variant 2 allows you to reduce the creation of objects at runtime. In this technique the use of the
microprocessor is reduced but the amount of memory used increases. The JVM garbage collector
has little work, since there are no objects not referenced at runtime.
Programmers must decide between variant 1 or variant 2, depending on the requirements of the
system and the problem to be solved.
The following lines of code belong to the layer that has the client role, since it is the layer that
underwent the modifications of variant 2. The rest of the source code is identical to variant 1.
package app;
import patron.Figura;
import patron.Rectangulo;
import patron.TrianguloRectangulo;
public Main() {
super();
}
The next line of code creates a new object in memory using the constructor called Rectangulo(),
that object will be pointed by the reference called rectangulo.
The following code executes the polymorphic method called polimorfismo(), with the argument of
type rectangle.
Página 80 de 130
POLYMORPHISM IN JAVA
polimorfismo(rectangulo);
The next line of code creates a new object in memory using the constructor called
TrianguloRectangulo(), that object will be pointed by the reference called
trianguloRectangulo.
The following code executes the polymorphic method called polimorfismo(), with the argument of
the type of triangles that are rectangles.
polimorfismo(trianguloRectangulo);
}
The following lines of code are the declaration of the dynamic polymorphic method called
polimorfismo(), dynamic polymorphic methods are characterized by having parameters of one
type and arguments of another type. The parameter represents the figures in a generic way. The
arguments of the parameter can be of the particular type: rectangle and triangle-rectangle.
Polymorphic methods that are dynamic have polymorphic algorithms that are also dynamic;
polymorphic algorithms that are dynamic are characterized by invoking different behaviors
depending on the argument of the parameter. Polymorphic methods that are dynamic send
messages to classes that have the role of providers. The classes that have the role of clients
implement algorithms that are polymorphic and the classes that have the role of providers
implement behavioral algorithms that are specialized. The main characteristic of algorithms that
are polymorphic is that their behavior and the sending of messages are defined at runtime.
The following code is correct and demonstrates that it is feasible to overload the parameter of the
polimorfismo() method with two different types of arguments.
Página 81 de 130
POLYMORPHISM IN JAVA
// //acceder a los métodos de la clase TrianguloRectangulo{}, si es
necesario
//
// }
Important note:
Methods and algorithms that are polymorphic must be implemented in the classes that are clients of
the design pattern; the design pattern is a hierarchy of related classes through inheritance.
Algorithms that are specialized must be implemented in the design pattern. The programmers will
make responsible the subclasses or the superclass of the implementation of the specialized
algorithms. Classes that have the role of clients benefit from implementing the algorithms based
on sending messages by reducing their code and reusing it. The design pattern must decide which
algorithm to execute depending on the parameters and the arguments of the message that has
been received.
In configuration 3.2, two constraints are introduced that force the architecture to work properly and
also force a good use of the design pattern based on the inheritance between classes.
Página 82 de 130
POLYMORPHISM IN JAVA
What is the dynamic assignment of the reference?
It is when a reference is assigned to more than one object during the entire execution of the
application. In this type of assignment, the JVM has a lot of work since it must clean objects not
referenced in the memory.
To use the mechanism of polymorphism, messages are sent to objects through an interface with
public methods. Each object must implement the same methods interface.
Página 83 de 130
POLYMORPHISM IN JAVA
Class diagram in Java for configuration 3.2 - variant 1
Página 84 de 130
POLYMORPHISM IN JAVA
Source code for configuration 3.2 - variant 1
package app;
import java.awt.Color;
import patron.Figura;
import patron.Rectangulo;
import patron.TrianguloRectangulo;
Página 85 de 130
POLYMORPHISM IN JAVA
//Este es un método polimórfico estático, un método polimórfico estático
tiene el parámetro y el argumento del mismo tipo.
}
*/
}
package patron;
import java.awt.Color;
@Override
public Integer area() {
//Los programadores han decido que el cálculo de área
// quede a cargo de la superclase
if(this.getClass().getName().equalsIgnoreCase(Rectangulo.class.getName())) {
return altura * base;
}else{
return (altura * base) / 2;
}
}
@Override
public Color getColor() {
Página 86 de 130
POLYMORPHISM IN JAVA
// TODO Implement this method
return color;
}
@Override
public void setColor(Color color) {
// TODO Implement this method
this.color = color;
}
}
package patron;
import java.awt.Color;
@Override
public Color getColor() {
// TODO Implement this method
return super.getColor();
}
@Override
public void setColor(Color color) {
// TODO Implement this method
super.setColor(color);
}
}
package patron;
import java.awt.Color;
Página 87 de 130
POLYMORPHISM IN JAVA
@Override
public Color getColor() {
// TODO Implement this method
return super.getColor();
}
@Override
public void setColor(Color color) {
// TODO Implement this method
super.setColor(color);
}
}
package patron;
import java.awt.Color;
Página 88 de 130
POLYMORPHISM IN JAVA
Class diagram in Java for configuration 3.2 - variant 2
Página 89 de 130
POLYMORPHISM IN JAVA
Source code for configuration 3.2 - variant 2
package app;
import java.awt.Color;
import patron.Figura;
import patron.Rectangulo;
import patron.TrianguloRectangulo;
}
*/
Página 90 de 130
POLYMORPHISM IN JAVA
}
package patron;
import java.awt.Color;
package patron;
import java.awt.Color;
@Override
public void setColor(Color color) {
// TODO Implement this method
super.setColor(color);
}
Página 91 de 130
POLYMORPHISM IN JAVA
@Override
public Color getColor() {
// TODO Implement this method
return super.getColor();
}
}
package patron;
import java.awt.Color;
@Override
public Color getColor() {
// TODO Implement this method
return super.getColor();
}
@Override
public void setColor(Color color) {
// TODO Implement this method
super.setColor(color);
}
}
package patron;
import java.awt.Color;
Página 92 de 130
POLYMORPHISM IN JAVA
Chapter III
It is the ability of the methods to have parameters declared with an interface and the arguments of
the parameters created with subclasses or superclasses.
An interface is an abstract class where all its methods are abstract and all its fields are constant. The
interfaces do not implement the source code; the code must be implemented by the classes that
inherit the interface. The interfaces are inherited using the Java keyword: implements.
There are different combinations with respect to the classes that can implement the interface.
Combination number 1:
The interface is implemented by the superclass
o The references are declared with the interfaces
o Objects are created by the superclass or subclasses
The combination number 1, allows the mutability of the reference between the created objects with
the subclasses and the superclass.
Página 93 de 130
POLYMORPHISM IN JAVA
Combination number 2:
The interface is implemented by subclasses
o The references are declared with the interfaces
o Objects are created with subclasses
The combination number 2, does not allow the mutability of the reference between the objects
created with the subclasses and the superclass. The combination number 2 only allows you to
create objects with subclasses.
Despite the impossibility of not creating objects from the superclass, it is still possible to create
dynamic polymorphic algorithms using the combination number 2. Dynamic polymorphic
algorithms were studied in chapters I and II.
Next, the class diagrams for variant number 1 of the combinations numbers 1 and 2 will be
presented. The reader should make an effort and try to implement variant number 2.
The source code will not be commented, as there would be no new contributions to the comments
made previously.
Página 94 de 130
POLYMORPHISM IN JAVA
Class diagram for polymorphic algorithms that are mutable. Combination 1 - variant 1
Página 95 de 130
POLYMORPHISM IN JAVA
Source code that implements mutable polymorphic algorithms. Combination 1 - variant 1
package app;
import patron.CalcularArea;
import patron.Figura;
import patron.Rectangulo;
import patron.TrianguloRectangulo;
public Main() {
super();
}
Página 96 de 130
POLYMORPHISM IN JAVA
System.out.println(" Altura = " + calcularArea.getAltura());
System.out.println(" Base = " + calcularArea.getBase());
System.out.println(" Área = " + calcularArea.area());
}//Fin del método polimórfico dinámico mutable.
package patron;
import java.awt.Color;
package patron;
import java.awt.Color;
@Override
public Integer getAltura() {
return altura;
}
@Override
public Integer getBase() {
return base;
}
Página 97 de 130
POLYMORPHISM IN JAVA
@Override
public Color getColor() {
return color;
}
if(this.getClass().getName().equalsIgnoreCase(Rectangulo.class.getName(
))) {
return altura * base;
}
if(this.getClass().getName().equalsIgnoreCase(TrianguloRectangulo.class
.getName())) {
return (altura * base) / 2;
}
package patron;
import java.awt.Color;
@Override
public Color getColor() {
// TODO Implement this method
return super.getColor();
}
Página 98 de 130
POLYMORPHISM IN JAVA
@Override
public Integer area() {
// TODO Implement this method
//Opción 1 (recomendada): La clase Rectangulo{} implementa su
propio algoritmo del cálculo del área.
return super.getAltura() * super.getBase();
package patron;
import java.awt.Color;
@Override
public Color getColor() {
// TODO Implement this method
return super.getColor();
}
@Override
public Integer area() {
// TODO Implement this method
//Opción 1 (recomendada): La clase TrianguloRectangulo{}
implementa su propio algoritmo del cálculo del área.
return (super.getAltura() * super.getBase()) / 2;
Página 99 de 130
POLYMORPHISM IN JAVA
Class diagram in UML for mutable polymorphic algorithms. Combination 2 - variant 1
package app;
import patron.CalcularArea;
import patron.Rectangulo;
import patron.TrianguloRectangulo;
package patron;
import java.awt.Color;
package patron;
import java.awt.Color;
package patron;
import java.awt.Color;
@Override
public void setColor(Color color) {
// TODO Implement this method
super.setColor(color);
}
@Override
public Color getColor() {
// TODO Implement this method
return super.getColor();
}
}
package patron;
import java.awt.Color;
@Override
public Integer area() {
return (this.getAltura() * this.getBase()) / 2;
}
@Override
public Color getColor() {
// TODO Implement this method
return super.getColor();
}
@Override
public void setColor(Color color) {
// TODO Implement this method
super.setColor(color);
}
}
The following lines of code are a classic, computer game that applies polymorphic algorithms to
control the characters in the game. Each character in the game will implement the algorithms that
specialize in their behavior.
Configuration 3.2, variant number 1 of chapter II, will be used to write the source code of the game
"Fly to the end". It is proposed to the reader, as a challenge, to make the necessary changes in the
source code of the game to rewrite them as a mutable polymorphic algorithm discussed in
Chapter III.
In the class that has the role of client, a reference will be declared for each character in the game.
Each of the references will point to an object instance that will represent a character in the game.
The class that has the client role will implement a dynamic polymorphic method whose parameter
will be of a generic type. And the arguments will be of the types, particular, of each character of
the game.
The parameter of the polymorphic method will have the highest level of abstraction and will
represent all the characters of the game, and the arguments of the parameter will have the lowest
level of abstraction representing each of the characters in the game.
The following line of source code is polymorphic, the parameter is an object reference called
g2DMiLienzo and the arguments of the parameter can be of the type: Fondo{}, Nubes{},
Personaje{} o Pilares{}
The reference with the name of g2DMiLienzo is of the type: DatosJuego{}. And it will point to
instances of type objects: Fondo{}, Nubes{}, Personaje{} o Pilares{}
This line of code will be executed whenever it is necessary to paint an element on the game board.
Classes that have the role of being customers of the software design pattern benefit from reusing the
source code and simplifying the logic of the game.
Each time the line of polymorphic code is executed, the JVM will decide which specialized code it
will execute depending on the type of reference to instances of objects.
package vista;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import patron.EnlaceJugar;
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
}//GEN-END:initComponents
/**
* @param args the command line arguments
.UIManager
.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing
.UIManager
.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util
.logging
.Logger
.getLogger(VentanaPrincipal.class.getName())
.log(java.util
.logging
.Level
.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util
.logging
.Logger
.getLogger(VentanaPrincipal.class.getName())
.log(java.util
.logging
.Level
.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util
.logging
.Logger
.getLogger(VentanaPrincipal.class.getName())
Source code for the classes that implement the client module
package patron;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
jPanel1EnlaceVista = jPanel1Vista;
g2DjPanel1EnlaceVista = (Graphics2D)
jPanel1EnlaceVista.getGraphics();
//Full anti-alias
g2DMiLienzo.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
//g2DMiLienzo.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
}
nubeBuena = new Nubes(1);//Crear un objeto del tipo Nubes{}
usando la referencia del tipo DatosJuego{}
@Override
public void run() {
// TODO Implement this method
super.run();
do {
try {
//pintar el fondo
pintarPolimorfismo(fondo);
//pintar las nubes
pintarPolimorfismo(nubeBuena);
pintarPolimorfismo(nubeMala);
//pintar los pilares
for(i=0; i<pilares.length;i++) {
pintarPolimorfismo(pilares[i]);
}
//pintar el personaje
pintarPolimorfismo(personaje);
//detectar colisiones del personaje con los pilares
for(i=0; i<pilares.length; i++) {
if(colisionPolimorfismo(pilares[i]) == true) {
break;
}
}
//detectar colisión del personaje con la nube mala
colisionPolimorfismo(nubeMala);
//Preguntar si hay vidas
esperarFinJuego = personaje.finJuego(g2DMiLienzo);
//pintar el lienzo personalizado en el lienzo de la vista
if(personaje.getRectangulo().intersects(quienColisiona.getRectangulo()))
{
//personaje.setColisiones(personaje.getColisiones()+1);
//aumentar colisiones
//personaje.setVidas(personaje.getVidas()-1); //disminuir una
vida
personaje.colision();
quienColisiona.setX(450); //poner objeto que colisiona en la
largada
return true;
}
return false;
}
queObjeto.pintarPolimorfismo(g2DMiLienzo);
if(queObjeto.getClass().getName().equals(Personaje.class.getName())) {
if(queObjeto.getClass().getName().equals(Pilares.class.getName())) {
}
//Pregunta si el objeto datosJuego es del tipo Nubes{}
if(queObjeto.getClass().getName().equals(Nubes.class.getName()))
{
}
//Pregunta si el objeto datosJuego es del tipo Fondo{}
if(queObjeto.getClass().getName().equals(Fondo.class.getName()))
{
}
}
//Este método es llamado desde la vista con la información del ratón
public void MouseClicked(java.awt.event.MouseEvent evt) {
boton = evt.getButton();
clicks = evt.getClickCount();
if(boton == 1) {
personaje.saltar(clicks);
}
}
//Este método es llamado desde la vista con la información del
teclado
public void KeyPressed(java.awt.event.KeyEvent evt) {
if(evt.getKeyCode() == evt.VK_SPACE) {
personaje.saltar(2);
}
}
}
Source code for classes that implement the specialized behavior provider
package patron;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
interface ComportamientoJuego {
package patron;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
@Override
public void setColisiones(int colisiones) {
// TODO Implement this method
//yo renuncio, se tiene que hacer cargo del comportamiento la
subclase
}
@Override
public int getVidas() {
// TODO Implement this method
return 0; //yo renuncio, se tiene que hacer cargo del
comportamiento la subclase
}
@Override
public void saltar(int clicks) {
// TODO Implement this method
//yo renuncio, se tiene que hacer cargo del comportamiento la
subclase
}
@Override
public void setVidas(int vidas) {
// TODO Implement this method
//yo renuncio, se tiene que hacer cargo del comportamiento la
subclase
}
*/
@Override
public void colision() {
// TODO Implement this method
//yo renuncio, se tiene que hacer cargo del comportamiento la
subclase
}
//Este método puede ser ejecutado por cada subclase, para que exista
polimorfismo hay que
// garantizar mensajes únicos para cada subclase, en este caso la
superclase obliga
// a las subclases a sobrescribir el método
pintarPolimorfismo(Graphics2D g2DMiLienzo).
//Cada subclase implementará un algoritmo diferente para pintar en un
único lienzo.
//Las instancias creadas usan los algoritmos de las subclases, pero
si el programador quiere puede
}
nombreSubclase = Nubes.class.getName();
if(miNombre.equals(nombreSubclase)){
//programar para la clase Nubes{}
}
nombreSubclase = Personaje.class.getName();
if(miNombre.equals(nombreSubclase)){
//programar para la clase Personaje{}
}
nombreSubclase = Pilares.class.getName();
if(miNombre.equals(nombreSubclase)){
//programar para la clase Pilares{}
}
}
@Override
public int finJuego(Graphics2D g2DMiLienzo) {
// TODO Implement this method
return 0; //yo renuncio, se tiene que hacer cargo del
comportamiento la subclase
}
@Override
public void saltar(int clicks) {
// TODO Implement this method
//yo renuncio, se tiene que hacer cargo del comportamiento la
subclase
}
}
package patron;
import java.awt.Graphics2D;
import java.awt.Image;
import javax.swing.ImageIcon;
@Override
public void run() {
// TODO Implement this method
super.run();
do {
try {
//Implementar todo el código necesario para animar el
fondo
Thread.sleep(getFps());
} catch (InterruptedException e) {
}
}while(true);
}
Image getImgFondo() {
return imgFondo.getImage();
}
@Override
public void pintarPolimorfismo(Graphics2D g2DMiLienzo) {
// TODO Implement this method
//super.pintarPolimorfismo(g2DMiLienzo); //la superclase ha
renunciado
g2DMiLienzo.drawImage(getImgFondo(), 0, 0, 400, 400, null);
}
}
package patron;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.util.Random;
import javax.swing.ImageIcon;
Nubes(int n) {
super();
@Override
public void run() {
// TODO Implement this method
super.run();
do {
setX(getX() - 2);
if(getX() < -150){
setX(450);
setY((aleatorio.nextInt(250)+50));
}
try {
Thread.sleep(getFps());
} catch (InterruptedException e) {
}
}while(true);
}
@Override
public int getAltura() {
// TODO Implement this method
return super.getAltura();
}
@Override
public int getAncho() {
// TODO Implement this method
return super.getAncho();
}
@Override
public int getFps() {
// TODO Implement this method
return super.getFps();
}
@Override
public int getX() {
// TODO Implement this method
@Override
public int getY() {
// TODO Implement this method
return super.getY();
}
@Override
public void setAltura(int altura) {
// TODO Implement this method
super.setAltura(altura);
}
@Override
public void setAncho(int ancho) {
// TODO Implement this method
super.setAncho(ancho);
}
@Override
public void setX(int x) {
// TODO Implement this method
super.setX(x);
}
@Override
public void setY(int y) {
// TODO Implement this method
super.setY(y);
}
@Override
public void setFps(int fps) {
// TODO Implement this method
super.setFps(fps);
}
@Override
public Rectangle getRectangulo() {
// TODO Implement this method
return super.getRectangulo(30);
}
@Override
public void pintarPolimorfismo(Graphics2D g2DMiLienzo) {
// TODO Implement this method
//super.pintarPolimorfismo(g2DMiLienzo); //la superclase ha
renunciado
g2DMiLienzo.drawImage(nubeImage, getX(), getY(), getAncho(),
getAltura(), null);
}
}
package patron;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;
@Override
public void run() {
// TODO Implement this method
super.run();
do {
try {
if(getY()<tope){
tope=50;
z=salto;
setY(getY()+salto);
}
if(getY()<=50) {
setY(55);
z=salto;
}
if(getY()>300){
z=0;//z=-salto;
setY(getY()-2);
}
setY(getY()+z);
Thread.sleep(getFps());
} catch (InterruptedException e) {
}
}while(true);
}
@Override
public int getY() {
// TODO Implement this method
return super.getY();
}
@Override
public void saltar(int clicks) {
@Override
public int getAltura() {
// TODO Implement this method
return super.getAltura();
}
@Override
public int getAncho() {
// TODO Implement this method
return super.getAncho();
}
@Override
public int getX() {
// TODO Implement this method
return super.getX();
}
@Override
public Rectangle getRectangulo() {
// TODO Implement this method
return super.getRectangulo(5);
}
@Override
public void pintarPolimorfismo(Graphics2D g2DMiLienzo) {
// TODO Implement this method
//super.pintarPolimorfismo(g2DMiLienzo); //la superclase ha
renunciado
//Pintar personaje
g2DMiLienzo.setColor(new Color(Color.orange.getRGB()));
g2DMiLienzo.fillOval(45, getY(), getAltura(), getAncho());
g2DMiLienzo.setColor(new Color(Color.white.getRGB()));
g2DMiLienzo.drawOval(45, getY(), getAltura(), getAncho());
g2DMiLienzo.setColor(new Color(Color.blue.getRGB()));
g2DMiLienzo.fillOval(60, getY()+3, 10, 10);
g2DMiLienzo.setColor(new Color(Color.white.getRGB()));
g2DMiLienzo.fillOval(65, getY()+6, 4, 4);
//Pintar puntuación
g2DMiLienzo.setColor(new Color(Color.white.getRGB()));
g2DMiLienzo.drawString(" Vidas = " + vidas, 11, 26);
g2DMiLienzo.setColor(new Color(Color.black.getRGB()));
g2DMiLienzo.drawString(" Vidas = " + vidas, 10, 25);
}
public int finJuego(Graphics2D g2DMiLienzo) {
if(vidas==0){
vidas=10;
@Override
public void colision() {
// TODO Implement this method
//super.colision(); //la superclase ha renunciado
vidas--;
}
}
package patron;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.util.Random;
Pilares(int n) {
super();
this.n=n;
setFps(1000 / (aleatorio.nextInt(30) + 30));
setAncho(aleatorio.nextInt(25)+25);
setAltura(aleatorio.nextInt(75)+100);
setX(aleatorio.nextInt(400)+400);
setY(aleatorio.nextInt(2) * (400-getAltura()));
color = new
Color(aleatorio.nextInt(255),aleatorio.nextInt(255),aleatorio.nextInt(255
));
}
@Override
public void run() {
// TODO Implement this method
super.run();
do {
try {
setX(getX()-2);
if(getX()<-50) {
setX(450);
setAltura(aleatorio.nextInt(75)+100);
setY(aleatorio.nextInt(2) * (400-getAltura()));
setX(aleatorio.nextInt(400)+400);
}
@Override
public int getY() {
// TODO Implement this method
return super.getY();
}
@Override
public int getX() {
// TODO Implement this method
return super.getX();
}
@Override
public int getAltura() {
// TODO Implement this method
return super.getAltura();
}
@Override
public void setX(int x) {
// TODO Implement this method
super.setX(x);
}
@Override
public int getAncho() {
// TODO Implement this method
return super.getAncho();
}
@Override
public Rectangle getRectangulo() {
// TODO Implement this method
return super.getRectangulo(5);
}
@Override
public void pintarPolimorfismo(Graphics2D g2DMiLienzo) {
// TODO Implement this method
//super.pintarPolimorfismo(g2DMiLienzo); //la superclase ha
renunciado
g2DMiLienzo.setColor(color);
g2DMiLienzo.fill3DRect(getX(), getY(), getAncho(), getAltura(),
true);
}
}
The structures formed by the classes that are related by means of inheritance, are a very simple and
basic structure. This structure is a design pattern to solve problems in the development of
software products.
There are many other design patterns that can be used to solve problems; the following design
patterns are the most studied and mentioned in the specialized literature.
Many of the design patterns mentioned above use the inheritance relationship to build the structures
that define them. These design patterns deserve a detailed study of the possibilities they have in
the generation of polymorphic algorithms.