Skip to content

Instantly share code, notes, and snippets.

@tiagodalloca
Created April 2, 2019 14:30
Show Gist options
  • Save tiagodalloca/cce4bdb57e8e53ccb9412eff3fc72d1a to your computer and use it in GitHub Desktop.
Save tiagodalloca/cce4bdb57e8e53ccb9412eff3fc72d1a to your computer and use it in GitHub Desktop.
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Retomando o Polimorfismo no Polígono\n",
"\n",
"Reveja a seguir o exemplo de polimorfismo e amarração dinâmica em C++. Estude este exemplo e tente escrevê-lo em Java na célula abaixo.\n",
"\n",
"Algumas coisas importantes:\n",
"* Em linguagens OO modernas como o Java os ponteiros estão sempre presentes implicitamente.\n",
"* Em linguagens OO modernas como o Java a amarração é sempre dinâmica, portanto, ela não precisa ser declarada explicitamente, a exemplo de como é feito com o `virtual` em C++.\n",
"\n",
"~~~cpp\n",
"#include <iostream>\n",
"\n",
"class Poligono {\n",
" private:\n",
" int altura;\n",
" int largura;\n",
" public:\n",
" Poligono(int altura, int largura) {\n",
" this->altura = altura;\n",
" this->largura = largura;\n",
" }\n",
" \n",
" int getAltura() {\n",
" return altura;\n",
" }\n",
" \n",
" int getLargura() {\n",
" return largura;\n",
" }\n",
" \n",
" virtual float getArea() {\n",
" return 0;\n",
" }\n",
"};\n",
"\n",
"class TrianguloRetangulo : public Poligono {\n",
" public:\n",
" TrianguloRetangulo(int altura, int largura) : Poligono(altura, largura) {\n",
" }\n",
" float getArea() {\n",
" return getAltura() * getLargura() / 2;\n",
" }\n",
"};\n",
"\n",
"class Retangulo : public Poligono {\n",
" public:\n",
" Retangulo(int altura, int largura) : Poligono(altura, largura) {\n",
" }\n",
" float getArea() {\n",
" return getAltura() * getLargura();\n",
" }\n",
"};\n",
"\n",
"Poligono *tr = new TrianguloRetangulo(6, 10);\n",
"Poligono *rt = new Retangulo(6, 10);\n",
"\n",
"std::cout << \"Área do triangulo retângulo: \" << tr->getArea() << std::endl;\n",
"std::cout << \"Área do retângulo: \" << rt->getArea() << std::endl;\n",
"~~~"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Exercício\n",
"\n",
"Escreva o exemplo acima em Java."
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Área do triangulo retângulo: 30.0\n",
"Área do retângulo: 60.0\n"
]
}
],
"source": [
"class Poligono {\n",
"\tprivate int altura;\n",
"\tprivate int largura;\n",
"\tpublic Poligono(int altura, int largura) {\n",
"\t\tthis.altura = altura;\n",
"\t\tthis.largura = largura;\n",
"\t}\n",
" \n",
"\tpublic int getAltura() {\n",
"\t\treturn altura;\n",
"\t}\n",
" \n",
"\tpublic int getLargura() {\n",
"\t\treturn largura;\n",
"\t}\n",
" \n",
"\tpublic float getArea() {\n",
"\t\treturn 0;\n",
"\t}\n",
"}\n",
"\n",
"class TrianguloRetangulo extends Poligono {\n",
"\tpublic TrianguloRetangulo(int altura, int largura){\n",
"\t\tsuper(altura, largura);\n",
"\t}\n",
"\tpublic float getArea() {\n",
"\t\treturn getAltura() * getLargura() / 2;\n",
"\t}\n",
"}\n",
"\n",
"class Retangulo extends Poligono {\n",
"\tpublic Retangulo(int altura, int largura){\n",
"\t\tsuper(altura, largura);\n",
"\t}\n",
"\tpublic float getArea() {\n",
"\t\treturn getAltura() * getLargura();\n",
"\t}\n",
"}\n",
"\n",
"Poligono tr = new TrianguloRetangulo(6, 10);\n",
"Poligono rt = new Retangulo(6, 10);\n",
"System.out.println(\"Área do triangulo retângulo: \" + tr.getArea());\n",
"System.out.println(\"Área do retângulo: \" + rt.getArea());"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Resolução\n",
"\n",
"Você deve ter construído algo como na solução a seguir."
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Área do triangulo retângulo: 30.0\n",
"Área do retângulo: 60.0\n"
]
}
],
"source": [
"class Poligono {\n",
" private int altura;\n",
" private int largura;\n",
"\n",
" \n",
" public Poligono(int altura, int largura) {\n",
" this.altura = altura;\n",
" this.largura = largura;\n",
" }\n",
" \n",
" int getAltura() {\n",
" return altura;\n",
" }\n",
" \n",
" int getLargura() {\n",
" return largura;\n",
" }\n",
" \n",
" float getArea() {\n",
" return 0;\n",
" }\n",
"}\n",
"\n",
"class TrianguloRetangulo extends Poligono {\n",
" public TrianguloRetangulo(int altura, int largura) {\n",
" super(altura, largura);\n",
" }\n",
" \n",
" float getArea() {\n",
" return getAltura() * getLargura() / 2;\n",
" }\n",
"};\n",
"\n",
"class Retangulo extends Poligono {\n",
" public Retangulo(int altura, int largura) {\n",
" super(altura, largura);\n",
" }\n",
" \n",
" float getArea() {\n",
" return getAltura() * getLargura();\n",
" }\n",
"};\n",
"\n",
"Poligono tr = new TrianguloRetangulo(6, 10);\n",
"Poligono rt = new Retangulo(6, 10);\n",
"\n",
"System.out.println(\"Área do triangulo retângulo: \" + tr.getArea());\n",
"System.out.println(\"Área do retângulo: \" + rt.getArea());"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# `toString()` no Garoto Zumbi\n",
"\n",
"Veja abaixo como a classe `GarotoZumbi` foi modificada. O método `mostra()` que mostrava o zumbi no console foi substituído pelo método `toString()` que retorna uma String com o desenho do zumbi (mas não o imprime). Com essa nova versão, você precisa receber e imprimir no console da seguinte maneira:\n",
"\n",
"~~~java\n",
"System.out.println(garoto.toString());\n",
"~~~\n",
"\n",
"Os outros métodos também deixaram de imprimir o desenho do zumbi e agora você precisa fazê-lo explicitamente."
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
" o*o\n",
"Asdrubal\n",
"\n",
" -*-\n",
"Asdrubal\n",
"\n",
" *\n",
" -*-\n",
"Asdrubal\n",
"\n"
]
}
],
"source": [
"public class GarotoZumbi\n",
"{\n",
" protected int idade;\n",
" protected String estado;\n",
" protected String nome;\n",
" \n",
" public GarotoZumbi(int idade, String estado, String nome) {\n",
" this.idade = idade;\n",
" this.estado = estado;\n",
" this.nome = nome;\n",
" }\n",
" \n",
" public String toString(boolean imprimeNome) {\n",
" String resultado = \"\";\n",
" \n",
" // cabeleira\n",
" if (idade >= 2)\n",
" resultado += \" *\\n\";\n",
" \n",
" // corpo com olhos\n",
" if (estado.equalsIgnoreCase(\"acordado\"))\n",
" resultado += \" o*o\\n\";\n",
" else\n",
" resultado += \" -*-\\n\";\n",
" \n",
" // barba\n",
" if (idade >= 3)\n",
" resultado += \"*****\\n\";\n",
" \n",
" if (imprimeNome)\n",
" resultado += nome + \"\\n\";\n",
" \n",
" return resultado;\n",
" }\n",
" \n",
" public String toString() {\n",
" return toString(true);\n",
" }\n",
" \n",
" public void cresce() {\n",
" if (idade < 3)\n",
" idade++;\n",
" }\n",
" \n",
" public void acorda() {\n",
" estado = \"acordado\";\n",
" }\n",
" \n",
" public void dorme() {\n",
" estado = \"dormindo\";\n",
" }\n",
"}\n",
"\n",
"GarotoZumbi garoto = new GarotoZumbi(1, \"acordado\", \"Asdrubal\");\n",
"System.out.println(garoto.toString());\n",
"garoto.dorme();\n",
"System.out.println(garoto.toString());\n",
"garoto.cresce();\n",
"System.out.println(garoto.toString());"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Método `toString()` de `Object`\n",
"\n",
"O nome do método `toString()` não foi escolhido por acaso. Ele é um método que está defininido na classe especial `Object`, que é aquela classe de onde descencem implicitamente todas as classes. Quando você não sobrescreve o método `toString()` ele retorna uma String o endereço do objeto na memória.\n",
"\n",
"O método `toString()` é chamado implicitamente toda vez que você pede para imprimir um objeto sem indicar o método, portanto, no exemplo a seguir:\n",
"\n",
"~~~java\n",
"Poligono tr = new TrianguloRetangulo(6, 10);\n",
"System.out.println(tr);\n",
"Poligono rt = new Retangulo(6, 10);\n",
"System.out.println(rt);\n",
"~~~\n",
"\n",
"Ele imprime umas sequências estranhas que são a identificação única do objeto na memória.\n",
"\n",
"Entretanto, se você sobrescreve o método `toString()`, através do polimorfismo, o novo método será chamado implicitamente quando você pede para imprimir o objeto. Por exemplo:\n",
"\n",
"~~~java\n",
"GarotoZumbi garoto = new GarotoZumbi(1, \"acordado\", \"Asdrubal\");\n",
"System.out.println(garoto);\n",
"garoto.dorme();\n",
"System.out.println(garoto);\n",
"garoto.cresce();\n",
"System.out.println(garoto);\n",
"~~~\n",
"\n",
"Imprime o desenho do `GarotoZumbi`."
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"REPL.$JShell$27B$TrianguloRetangulo@4473e500\n",
"REPL.$JShell$29B$Retangulo@6c9d3e55\n",
"===============================\n",
" o*o\n",
"Asdrubal\n",
"\n",
"\n",
" -*-\n",
"Asdrubal\n",
"\n",
"\n",
" *\n",
" -*-\n",
"Asdrubal\n",
"\n",
"\n"
]
}
],
"source": [
"Poligono tr = new TrianguloRetangulo(6, 10);\n",
"System.out.println(tr);\n",
"Poligono rt = new Retangulo(6, 10);\n",
"System.out.println(rt);\n",
"\n",
"System.out.println(\"===============================\");\n",
"\n",
"GarotoZumbi garoto = new GarotoZumbi(1, \"acordado\", \"Asdrubal\");\n",
"System.out.println(garoto);\n",
"garoto.dorme();\n",
"System.out.println(garoto);\n",
"garoto.cresce();\n",
"System.out.println(garoto);"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercício\n",
"\n",
"Considere os herdeiros `Monstro` e `Perfeito` abaixo implementados à moda antiga com o método `mostra()` (eles não funcionarão agora se você tentar executá-los porque a superclasse -- `GarotoZumbi` -- não tem mais o `mostra()`).\n",
"\n",
"Adapte ambos para que passem a ter o método `toString()` que retorna o desenho na forma de String, substituindo o `mostra()`."
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
" o*o\n",
"Bonerges\n",
"\n",
" *\n",
" o*o\n",
"Bonerges\n",
"\n",
" *\n",
" o*o\n",
"*****\n",
"Bonerges\n",
"\n",
" *\n",
" o*o\n",
"*****\n",
"#####\n",
"Bonerges\n",
"\n",
" *\n",
" o*o\n",
"*****\n",
"#####\n",
"/ \\\n",
"Bonerges\n",
"\n",
" *\n",
" o*o\n",
"*****\n",
"#####\n",
"/ \\\n",
"Bonerges\n",
"\n",
" *\n",
" -*-\n",
"*****\n",
"#####\n",
"/ \\\n",
"Bonerges\n",
"\n"
]
}
],
"source": [
"public class Monstro extends GarotoZumbi\n",
"{\n",
" public Monstro(int idade, String estado, String nome) {\n",
" super(idade, estado, nome);\n",
" }\n",
"\n",
" public String toString(boolean imprimeNome) {\n",
"\t\t\tString acc = super.toString(false);\n",
"\n",
"\t\t\tif (idade >= 4) acc += \"#####\\n\";\n",
"\t\t\tif (idade >= 5) acc += \"/ \\\\\\n\";\n",
"\n",
"\t\t\tif (imprimeNome) acc += nome + \"\\n\";\n",
" \n",
" return acc;\n",
"\t\t}\n",
"\n",
" public void cresce() {\n",
" if (idade < 5)\n",
" idade++;\n",
" }\n",
"}\n",
"\n",
"Monstro monst = new Monstro(1, \"acordado\", \"Bonerges\");\n",
"System.out.println(monst.toString());\n",
"monst.cresce();\n",
"System.out.println(monst.toString());\n",
"monst.cresce();\n",
"System.out.println(monst.toString());\n",
"monst.cresce();\n",
"System.out.println(monst.toString());\n",
"monst.cresce();\n",
"System.out.println(monst.toString());\n",
"monst.cresce();\n",
"System.out.println(monst.toString());\n",
"monst.dorme();\n",
"System.out.println(monst.toString());"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"+-----+\n",
"| o-o |\n",
"| ___ |\n",
" \\___/\n",
"Zandor\n",
"\n",
"| |\n",
"| o-o |\n",
"| ___ |\n",
" \\___/\n",
"Zandor\n",
"\n",
"| |\n",
"| o-o |\n",
"| ___ |\n",
"| |\n",
"\\_____/\n",
"Zandor\n",
"\n",
"| |\n",
"| $-$ |\n",
"| ___ |\n",
"| |\n",
"\\_____/\n",
"Zandor\n",
"\n"
]
}
],
"source": [
"public class Perfeito extends GarotoZumbi\n",
"{\n",
"\tprivate String situacao = \"normal\";\n",
" \n",
"\tpublic Perfeito(int idade, String estado, String nome) {\n",
"\t\tsuper(idade, estado, nome);\n",
"\t}\n",
"\n",
"\tpublic Perfeito(int idade, String estado, String nome, String situacao) {\n",
"\t\tsuper(idade, estado, nome);\n",
"\t\tthis.situacao = situacao;\n",
"\t}\n",
"\n",
"\tpublic String toString(boolean imprimeNome) {\n",
"\t\tString acc = \"+-----+\\n\";\n",
"\n",
"\t\tif (idade >= 2)\n",
"\t\t\tacc = \"| |\\n\";\n",
"\n",
"\t\tif (estado.equals(\"dormindo\")) {\n",
"\t\t\tacc += \" - -\\n\";\n",
"\t\t\tacc += \"| _ |\\n\";\n",
"\t\t}\n",
"\t\telse if (situacao.equals(\"normal\")) {\n",
"\t\t\tacc += \"| o-o |\\n\";\n",
"\t\t\tacc += \"| ___ |\\n\";\n",
"\t\t}\n",
"\t\telse if (situacao.equals(\"milionario\")) {\n",
"\t\t\tacc += \"| $-$ |\\n\";\n",
"\t\t\tacc += \"| ___ |\\n\";\n",
"\t\t}\n",
"\t\telse if (situacao.equals(\"doido\")) {\n",
"\t\t\tacc += \"| @-@ |\\n\";\n",
"\t\t\tacc += \"| ~ |\\n\";\n",
"\t\t}\n",
"\n",
"\t\tif (idade < 3)\n",
"\t\t\tacc += \" \\\\___/\\n\";\n",
"\t\telse {\n",
"\t\t\tacc += \"| |\\n\";\n",
"\t\t\tacc += \"\\\\_____/\\n\";\n",
"\t\t}\n",
"\n",
"\t\tif (imprimeNome) acc += nome + \"\\n\";\n",
" return acc;\n",
"\t}\n",
"\n",
"\tpublic void mudaSituacao() {\n",
"\t\tString s[] = {\"normal\",\n",
"\t\t\t\t\t\t\t\t\t\"milionario\",\n",
"\t\t\t\t\t\t\t\t\t\"doido\" };\n",
"\n",
"\t\tint p;\n",
"\t\tfor (p = 0; p < s.length && !situacao.equals(s[p]); p++)\n",
"\t\t\t/* nada */ ;\n",
"\n",
"\t\tp = (p + 1) % 3;\n",
"\t\tsituacao = s[p];\n",
"\t}\n",
"}\n",
"\n",
"Perfeito perf = new Perfeito(1, \"acordado\", \"Zandor\");\n",
"System.out.println(perf.toString());\n",
"perf.cresce();\n",
"System.out.println(perf.toString());\n",
"perf.cresce();\n",
"System.out.println(perf.toString());\n",
"perf.mudaSituacao();\n",
"System.out.println(perf.toString());\n",
"perf.mudaSituacao();\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Exercício\n",
"\n",
"Dada a classe `Servicos`, a seguir, crie nela um método estático chamado `imprimeZumbi`. Esse método deve receber como parâmetro uma referência para um objeto da classe `GarotoZumbi` (considere a nova versão com `toString()`), ou um de seus herdeiros, e deve imprimi-lo.\n",
"\n",
"Utilize uma solução que explore o polimorfismo, sem o uso de condicional."
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"+-----+\n",
"| o-o |\n",
"| ___ |\n",
" \\___/\n",
"Zandor\n",
"\n",
"| |\n",
"| o-o |\n",
"| ___ |\n",
" \\___/\n",
"Zandor\n",
"\n",
"| |\n",
"| o-o |\n",
"| ___ |\n",
"| |\n",
"\\_____/\n",
"Zandor\n",
"\n",
"| |\n",
"| $-$ |\n",
"| ___ |\n",
"| |\n",
"\\_____/\n",
"Zandor\n",
"\n",
"| |\n",
"| @-@ |\n",
"| ~ |\n",
"| |\n",
"\\_____/\n",
"Zandor\n",
"\n"
]
}
],
"source": [
"public class Servicos {\n",
" public static void imprimeZumbi(GarotoZumbi z){\n",
" System.out.println(z.toString());\n",
" }\n",
"}\n",
"\n",
"Perfeito perf = new Perfeito(1, \"acordado\", \"Zandor\");\n",
"Servicos.imprimeZumbi(perf);\n",
"perf.cresce();\n",
"Servicos.imprimeZumbi(perf);\n",
"perf.cresce();\n",
"Servicos.imprimeZumbi(perf);\n",
"perf.mudaSituacao();\n",
"Servicos.imprimeZumbi(perf);\n",
"perf.mudaSituacao();\n",
"Servicos.imprimeZumbi(perf);"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Exercício\n",
"\n",
"Dada a classe `EmprestimoComposto` desenvolvida anteriormente em sala de aula.\n",
" \n",
"Crie uma classe `Emprestimo` que generalize qualquer emprestimo e `EmprestimoComposto` passa a ser herdeira da mesma. Transfira para a superclasse o máximo de atributos e métodos, de tal modo que possam ser reusados pelos herdeiros.\n",
"\n",
"Crie uma classe `EmprestimoSimples` herdeira de `Emprestimo` que também disponha dos métodos `parcela()` e `proximaParcela()`."
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Emprestimo 1: parcela 1 eh 200.0\n",
" parcela 1 eh 200.0\n",
"Emprestimo 2: parcela 1 eh 500.0\n",
" parcela 1 eh 500.0\n",
"Emprestimo 1: parcela 2 eh 202.0\n",
" parcela 2 eh 202.0\n",
"Emprestimo 2: parcela 2 eh 510.0\n",
" parcela 2 eh 510.0\n",
"Emprestimo 1: parcela 3 eh 204.02\n",
" parcela 3 eh 204.02\n",
"Emprestimo 2: parcela 3 eh 520.2\n",
" parcela 3 eh 520.19995\n",
"Emprestimo 1: parcela 4 eh 206.06021\n",
" parcela 4 eh 206.0602\n",
"Emprestimo 2: parcela 4 eh 530.604\n",
" parcela 4 eh 530.60394\n",
"Emprestimo 1: parcela 5 eh 208.12082\n",
" parcela 5 eh 208.1208\n",
"Emprestimo 2: parcela 5 eh 541.21606\n",
" parcela 5 eh 541.216\n",
"Emprestimo 2: parcela 6 eh 552.0404\n",
" parcela 6 eh 552.04034\n",
"Emprestimo 2: parcela 7 eh 563.08124\n",
" parcela 7 eh 563.0811\n"
]
}
],
"source": [
"import java.lang.Math;\n",
"\n",
"class EmprestimoComposto {\n",
" private float s;\n",
" private int n;\n",
" private float j;\n",
" private int corrente;\n",
" private float p,\n",
" proxima;\n",
"\n",
" public EmprestimoComposto(float s, int n, float j) {\n",
" this.s = s;\n",
" this.n = n;\n",
" this.j = j;\n",
" corrente = 1;\n",
" this.p = -1; // antes da primeira parcela\n",
" this.proxima = s;\n",
" }\n",
"\n",
" int getN() {\n",
" return n;\n",
" }\n",
" \n",
" float getJ() {\n",
" return j;\n",
" }\n",
"\n",
" float getP() {\n",
" return p;\n",
" }\n",
"\n",
" public float proximaParcela() {\n",
" p = proxima;\n",
" corrente++;\n",
" if (corrente <= n)\n",
" proxima += (proxima * (j/100));\n",
" else\n",
" proxima = 0;\n",
" return p;\n",
" }\n",
" \n",
" public float parcela() {\n",
" return p;\n",
" }\n",
" \n",
" public float parcela(int numero) {\n",
" float resultado = 0;\n",
" if (numero <= n)\n",
" resultado = s * (float)Math.pow(1 + j/100, numero-1);\n",
" return resultado;\n",
" }\n",
"}\n",
"\n",
"// codigo principal\n",
"\n",
"EmprestimoComposto emprestimo1 = new EmprestimoComposto(200, 5, 1),\n",
" emprestimo2 = new EmprestimoComposto(500, 7, 2);\n",
"\n",
"int i = 1;\n",
"emprestimo1.proximaParcela();\n",
"emprestimo2.proximaParcela();\n",
"while (emprestimo1.parcela() > 0 || emprestimo2.parcela() > 0) {\n",
" if (emprestimo1.parcela() > 0) {\n",
" System.out.println(\"Emprestimo 1: parcela \" + i + \" eh \" + emprestimo1.parcela());\n",
" System.out.println(\" parcela \" + i + \" eh \" + emprestimo1.parcela(i));\n",
" }\n",
" if (emprestimo2.parcela() > 0) {\n",
" System.out.println(\"Emprestimo 2: parcela \" + i + \" eh \" + emprestimo2.parcela());\n",
" System.out.println(\" parcela \" + i + \" eh \" + emprestimo2.parcela(i));\n",
" }\n",
" emprestimo1.proximaParcela();\n",
" emprestimo2.proximaParcela();\n",
" i++;\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Emprestimo 1: parcela 1 eh 200.0\n",
" parcela 1 eh 200.0\n",
"Emprestimo 2: parcela 1 eh 500.0\n",
" parcela 1 eh 510.0\n",
"Emprestimo 1: parcela 2 eh 202.0\n",
" parcela 2 eh 202.0\n",
"Emprestimo 2: parcela 2 eh 1010.0\n",
" parcela 2 eh 520.0\n",
"Emprestimo 1: parcela 3 eh 204.02\n",
" parcela 3 eh 204.02\n",
"Emprestimo 2: parcela 3 eh 2030.0\n",
" parcela 3 eh 530.0\n",
"Emprestimo 1: parcela 4 eh 206.06021\n",
" parcela 4 eh 206.0602\n",
"Emprestimo 2: parcela 4 eh 4070.0\n",
" parcela 4 eh 540.0\n",
"Emprestimo 1: parcela 5 eh 208.12082\n",
" parcela 5 eh 208.1208\n",
"Emprestimo 2: parcela 5 eh 8150.0\n",
" parcela 5 eh 550.0\n",
"Emprestimo 2: parcela 6 eh 16310.0\n",
" parcela 6 eh 560.0\n",
"Emprestimo 2: parcela 7 eh 32630.0\n",
" parcela 7 eh 570.0\n"
]
}
],
"source": [
"import java.lang.Math;\n",
"\n",
"abstract class Emprestimo {\n",
"\tprotected float s;\n",
"\tprotected int n;\n",
"\tprotected float j;\n",
"\tprotected int corrente;\n",
"\tprotected float p, proxima;\n",
"\n",
"\tpublic Emprestimo(float s, int n, float j) {\n",
"\t\tthis.s = s;\n",
"\t\tthis.n = n;\n",
"\t\tthis.j = j;\n",
"\t\tcorrente = 1;\n",
"\t\tthis.p = -1; // antes da primeira parcela\n",
"\t\tthis.proxima = s;\n",
"\t}\n",
"\n",
"\tint getN() {\n",
"\t\treturn n;\n",
"\t}\n",
" \n",
"\tfloat getJ() {\n",
"\t\treturn j;\n",
"\t}\n",
"\n",
"\tfloat getP() {\n",
"\t\treturn p;\n",
"\t}\n",
"\n",
"\tabstract public float proximaParcela();\n",
"\tabstract public float parcela(int numero);\n",
" \n",
"\tpublic float parcela() {\n",
"\t\treturn p;\n",
"\t}\n",
"}\n",
"\n",
"\n",
"class EmprestimoComposto extends Emprestimo {\n",
"\n",
"\tpublic EmprestimoComposto(float s, int n, float j) {\n",
"\t\tsuper(s, n, j);\n",
"\t}\n",
"\n",
"\tpublic float proximaParcela() {\n",
" p = proxima;\n",
" corrente++;\n",
" if (corrente <= n)\n",
" proxima += (proxima * (j/100));\n",
" else\n",
" proxima = 0;\n",
" return p;\n",
" }\n",
"\t\n",
"\tpublic float parcela(int numero) {\n",
"\t\tfloat resultado = 0;\n",
"\t\tif (numero <= n)\n",
"\t\t\tresultado = s * (float)Math.pow(1 + j/100, numero-1);\n",
"\t\treturn resultado;\n",
"\t}\n",
"}\n",
"\n",
"class EmprestimoSimples extends Emprestimo {\n",
"\n",
"\tpublic EmprestimoSimples(float s, int n, float j) {\n",
"\t\tsuper(s, n, j);\n",
"\t}\n",
"\n",
"\tpublic float proximaParcela() {\n",
"\t\tp = proxima;\n",
"\t\tcorrente++;\n",
"\t\tif (corrente <= n)\n",
"\t\t\tproxima += proxima + s * (j/100);\n",
"\t\telse\n",
"\t\t\tproxima = 0;\n",
"\t\treturn p;\n",
"\t}\n",
"\t\n",
"\tpublic float parcela(int numero) {\n",
"\t\tfloat resultado = 0;\n",
"\t\tif (numero <= n)\n",
"\t\t\tresultado = s + numero*s*j/100;\n",
"\t\treturn resultado;\n",
"\t}\n",
"}\n",
"\n",
"\n",
"\n",
"// codigo principal\n",
"\n",
"EmprestimoComposto emprestimo1 = new EmprestimoComposto(200, 5, 1);\n",
"EmprestimoSimples\temprestimo2 = new EmprestimoSimples(500, 7, 2);\n",
"\n",
"int i = 1;\n",
"emprestimo1.proximaParcela();\n",
"emprestimo2.proximaParcela();\n",
"while (emprestimo1.parcela() > 0 || emprestimo2.parcela() > 0) {\n",
"\tif (emprestimo1.parcela() > 0) {\n",
"\t\tSystem.out.println(\"Emprestimo 1: parcela \" + i + \" eh \" + emprestimo1.parcela());\n",
"\t\tSystem.out.println(\" parcela \" + i + \" eh \" + emprestimo1.parcela(i));\n",
"\t}\n",
"\tif (emprestimo2.parcela() > 0) {\n",
"\t\tSystem.out.println(\"Emprestimo 2: parcela \" + i + \" eh \" + emprestimo2.parcela());\n",
"\t\tSystem.out.println(\" parcela \" + i + \" eh \" + emprestimo2.parcela(i));\n",
"\t}\n",
"\temprestimo1.proximaParcela();\n",
"\temprestimo2.proximaParcela();\n",
"\ti++;\n",
"}\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Exercício\n",
"\n",
"Escreva um programa que defina um vetor de `Emprestimos` que pode conter tanto instâncias de `EmprestimoSimples` quanto `EmprestimoComposto`. O programa deve percorrer o vetor e imprimir a próxima parcela de cada financiamento."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Java",
"language": "java",
"name": "java"
},
"language_info": {
"codemirror_mode": "java",
"file_extension": ".java",
"mimetype": "text/x-java-source",
"name": "Java",
"pygments_lexer": "java",
"version": "10.0.1+10-Debian-4"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment