Documentos de Académico
Documentos de Profesional
Documentos de Cultura
TEMA 4: “POLIMORFISMO”
SEMESTRE: 2. GRUPO: B.
FECHA: 22/06/2021.
Objetivo.
El objetivo de esta práctica de programación es construir una aplicación que
permita sumar dos fracciones y comparar cual de las dos es mayor o menor o si
ambas son iguales. De igual manera que permita sacar 2 longitudes a partir de
coordenadas digitadas por el usuario y que permita comparar entre las dos
longitudes cual es mayor o menor o si ambas son iguales.
Desarrollo.
Se codifica la aplicación directamente con ayuda de NetBeans cuidando que
cumpla con el paradigma de programación orientada a objetos, pero esta vez
aplicando la teoría de polimorfismo.
El programa consta con 2 paquetes los cuales son el backEnd y el frondEnd,
en el paquete backEnd se encuentran 3 clases la primera se trata de la clase
Quebrado(Broken), Linea(Line), Relaciones(Relation). Mientras que en el paquete
frondEnd se encuentran 2 clases que vienen siendo las interfaces de usuario las
cuales son BrokenAndLines (QuebradosYLineas) y LineInterface(LineaInterfaz).
Esto quedaría de la siguiente manera:
Paquete backEnd.
En este caso las clases, métodos y variables fueron traducidos al inglés para
conservar un código limpio y así cumplir con las buenas prácticas de programación.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package backEnd;
/**
*
* @author Brandon Omar Morales Solís
*/
public class Broken implements Relations {
/**
* Implements es parte del polimorfismo porque permite que se obtenga
* información a partir de un calse interface permitiendo la reutilización
* de código.
*
*/
//Atributos
private int numerator;
private int denominator;
//Método constructor para inicializar las variables con los valores nulos.
public Broken() {
numerator = 0;
denominator = 1;
}
//Método constructor
public Broken(int numerator, int denominator) {
this.numerator = numerator;
this.denominator = denominator;
}
/**
* Este método devuelve el Máximo Común Divisor obtenido por medio del
* Algoritmo de Euclides
*
* @return Máximo Común Divisor
*/
public int mcd() {
int u;
int v;
int r;
u = Math.abs(numerator);
v = Math.abs(denominator);
if (v == 0) {
return u;
}
while (v != 0) {
r = u % v;
u = v;
v = r;
}
return u;
}
/**
* Implementación del método abstracto de la interface Relaciones
*
* @param a es el valor a comparar
* @return True si es mayor, False en caso contrario
*/
@Override //Sirve para poder sobrecargar los métodos
//Es parte del polimorfismo porque permite usarlo cuántas veces uno lo desee.
Broken f = (Broken) a;
//this.simplify();
//f.simplify();
/**
* Implementación del método abstracto de la interface Relaciones
*
* @param a
* @return
*/
@Override
public boolean isLessThan(Relations a) {
if (a == null) {
return false;
}
Broken f = (Broken) a;
//this.simplify();
//f.simplify();
return (numerator / (double) denominator) < (f.numerator / (double)
f.denominator);
}
/**
* Implementación del método abstracto de la interface Relaciones
*
* @param a
* @return
*/
@Override
public boolean itsTheSameAs(Relations a) {
if (a == null) {
return false;
}
Broken f = (Broken) a;
//this.simplify();
//f.simplify();
if (numerator != f.numerator) {
return false;
}
if (denominator != f.denominator) {
return false;
}
return true;
}
/**
* Redefiniendo el método toString heredado de Object
*
* @return
*/
@Override
public String toString() {
//simplify();
return numerator + "/" + denominator;
}
/**
* @return the numerator
*/
public int getNumerator() {
return numerator;
}
/**
* @param numerator the numerator to set
*/
public void setNumerator(int numerator) {
this.numerator = numerator;
}
/**
* @return the denominator
*/
public int getDenominator() {
return denominator;
}
/**
* @param denominator the denominator to set
*/
public void setDenominator(int denominator) {
this.denominator = denominator;
}
}
Código de la clase Line.
En este caso las clases, métodos y variables fueron traducidos al inglés para
conservar un código limpio y así cumplir con las buenas prácticas de programación.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package backEnd;
/**
*
* @author Brandon Omar Morales Solís
*/
public class Line implements Relations {
/**
* Implements es parte del polimorfismo porque permite que se obtenga
* información a partir de un calse interface permitiendo la reutilización
* de código.
*
*/
//Atributos
private double x1;
private double y1;
private double x2;
private double y2;
//Método constructor para inicializar las variables con los valores nulos.
public Line() {
x1 = 0;
y1 = 0;
x2 = 0;
y2 = 0;
}
//Método constructor
public Line(double x1, double y1, double x2, double y2) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}
/**
* Este método devuelve la longitud que mide una linea a partir de 2 puntos
* x1,y1 a x2,y2
*
* @return longitud de la línea.
*/
public double length() {
double length;
length = Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
return length;
}
@Override
public boolean itsTheSameAs(Relations a) {
if (a == null) {
return false;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Coordenadas inicio linea: ");
sb.append(getX1());
sb.append(" , ");
sb.append(getY1());
sb.append("\nCoordenadas final linea: ");
sb.append(getX2());
sb.append(" , ");
sb.append(getY2());
sb.append("\nLongitud: ");
sb.append((length()));
return sb.toString();
}
/**
* @return the x1
*/
public double getX1() {
return x1;
}
/**
* @param x1 the x1 to set
*/
public void setX1(double x1) {
this.x1 = x1;
}
/**
* @return the y1
*/
public double getY1() {
return y1;
}
/**
* @param y1 the y1 to set
*/
public void setY1(double y1) {
this.y1 = y1;
}
/**
* @return the x2
*/
public double getX2() {
return x2;
}
/**
* @param x2 the x2 to set
*/
public void setX2(double x2) {
this.x2 = x2;
}
/**
* @return the y2
*/
public double getY2() {
return y2;
}
/**
* @param y2 the y2 to set
*/
public void setY2(double y2) {
this.y2 = y2;
}
@Override
public boolean isLessThan(Relations a) {
throw new UnsupportedOperationException("Not supported yet."); //To change
body of generated methods, choose Tools | Templates.
}
}
Código de la clase Relation (Relaciones).
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package backEnd;
/**
*
* @author Brandon Omar Morales Solís
*/
public interface Relations {
//Métodos
boolean isBetterThan(Relations a);
boolean isLessThan(Relations a);
boolean itsTheSameAs(Relations a);
Frames utilizados.
Código de la interfaz (BrokenAndLines).
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package fronEnd;
import backEnd.*;
import javax.swing.JOptionPane;
/**
*
* @author brand
*/
public class BrokenAndLines extends javax.swing.JFrame {
/**
* Creates new form BrokenAndLines
*/
public BrokenAndLines() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Broken ");
jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
lblComparison.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lblComparison.setToolTipText("");
jPanel1.add(lblComparison, new
org.netbeans.lib.awtextra.AbsoluteConstraints(110, 240, 210, 80));
jLabel1.setIcon(new
javax.swing.ImageIcon(getClass().getResource("/Imagenes/fracciones-
matematicas-olorful-sobre-fondo-violeta-matematicas-interesantes-para-los-ninos-
la-educacion-concepto-de-vuelta-a-la-escuela-geometria-y-matematicas-
materiales-w79n4r.jpg"))); // NOI18N
jPanel1.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0,
400, 380));
pack();
setLocationRelativeTo(null);
}// </editor-fold>
//Se guardan los datos del númerados y denominador con ayuda de los objetos
t1.setNumerator(Integer.parseInt(txtNumerator.getText()));
t1.setDenominator(Integer.parseInt(txtDenominator.getText()));
t2.setNumerator(Integer.parseInt(txtNumerator2.getText()));
t2.setDenominator(Integer.parseInt(txtDenominator2.getText()));
t3 = t1.sum(t2);
lblOutcome.setText(t3.toString());
}
if (exit == 0) {
System.exit(0);
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code
(optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look
and feel.
* For details see
http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info :
javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(BrokenAndLines.class.getName()).log(java.util.l
ogging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(BrokenAndLines.class.getName()).log(java.util.l
ogging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(BrokenAndLines.class.getName()).log(java.util.l
ogging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(BrokenAndLines.class.getName()).log(java.util.l
ogging.Level.SEVERE, null, ex);
}
//</editor-fold>
import backEnd.*;
import javax.swing.JOptionPane;
/**
*
* @author brand
*/
public class LineInterface extends javax.swing.JFrame {
/**
* Creates new form Line
*/
public LineInterface() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Line");
jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
lblComparison.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jPanel1.add(lblComparison, new
org.netbeans.lib.awtextra.AbsoluteConstraints(60, 500, 300, 60));
jLabel1.setIcon(new
javax.swing.ImageIcon(getClass().getResource("/Imagenes/matematicas-
978x652.jpg"))); // NOI18N
jPanel1.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0,
440, 600));
pack();
setLocationRelativeTo(null);
}// </editor-fold>
line1.setX1(Double.parseDouble(txtX1.getText()));
line1.setY1(Double.parseDouble(txtY1.getText()));
line1.setX2(Double.parseDouble(txtX2.getText()));
line1.setY2(Double.parseDouble(txtY2.getText()));
line2.setX1(Double.parseDouble(txtX_1.getText()));
line2.setY1(Double.parseDouble(txtY_1.getText()));
line2.setX2(Double.parseDouble(txtX_2.getText()));
line2.setY2(Double.parseDouble(txtY_2.getText()));
if (line1.isBetterThan(line2)) {
lblComparison.setText(line1.length() + " > " + line2.length());
} else {
lblComparison.setText(line1.length() + " < " + line2.length());
}
if (line1.itsTheSameAs(line2)) {
lblComparison.setText(line1.length() + " = " + line2.length());
}
lblLength.setText("" + line1.length());
lblLength2.setText("" + line2.length());
}
if (exit == 0) {
System.exit(0);
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code
(optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look
and feel.
* For details see
http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info :
javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(LineInterface.class.getName()).log(java.util.loggi
ng.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(LineInterface.class.getName()).log(java.util.loggi
ng.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(LineInterface.class.getName()).log(java.util.loggi
ng.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(LineInterface.class.getName()).log(java.util.loggi
ng.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
Resultados.
Conclusión.
Al haber hecho esta práctica de programación puedo concluir que si logramos
con el objetivo porque el programa permite sumar fracciones y comparar para ver
quien es mayor o menor que o si ambos son iguales. Al igual permite poder sacar
las longitudes a partir de cordenadas.
También puedo decir que gracias a esta practica aprendi a profundizar mas
en el polimorfismo porque aprendi que si se cuenta con una clase interface para
poder rutilizar el código que se encuentra en esa clase es necesario utilizar el
implements porque para este caso ya no funciona.
Otra cosa importante que aprendí es a poner imágenes de fondo a las
aplicaciones para que luzcan llamativas.
Referencias.
Reyes, G (2021). Clase Laboratorio. Teams. Recuperado de:
https://instectapachula.sharepoint.com/sites/POOGrupoB20212/Documentos%20c
ompartidos/General/Recordings/Clase%20de%20laboratorio_20210617_120919.m
p4