Repaso Estructuras Java Vs Python#

#@title Celda de configuración del notebook para Java
#@markdown  - Ejecute esta celda para configurar el entorno de java

%%bash
#!/usr/bin/env bash

echo "Update environment..."
apt update -q  &> /dev/null

echo "Install Java..."
apt-get install -q openjdk-11-jdk-headless &> /dev/null

echo "Install Jupyter java kernel..."
curl -L https://github.com/SpencerPark/IJava/releases/download/v1.3.0/ijava-1.3.0.zip \
 -o ijava-kernel.zip &> /dev/null

unzip -q ijava-kernel.zip -d ijava-kernel \
 && cd ijava-kernel \
 && python3 install.py --sys-prefix &> /dev/null

echo "Install proxy for the java kernel"
# NOTE: required after changes to Google Colab defaults in Dec. 2022
# See https://stackoverflow.com/questions/74674688/google-colab-notebook-using-ijava-stuck-at-connecting-after-installation-ref/74821762#74821762

wget -qO- https://gist.github.com/SpencerPark/e2732061ad19c1afa4a33a58cb8f18a9/archive/b6cff2bf09b6832344e576ea1e4731f0fb3df10c.tar.gz | tar xvz --strip-components=1
python install_ipc_proxy_kernel.py --kernel=java --implementation=ipc_proxy_kernel.py
Update environment...
Install Java...
Install Jupyter java kernel...
Install proxy for the java kernel
e2732061ad19c1afa4a33a58cb8f18a9-b6cff2bf09b6832344e576ea1e4731f0fb3df10c/install_ipc_proxy_kernel.py
e2732061ad19c1afa4a33a58cb8f18a9-b6cff2bf09b6832344e576ea1e4731f0fb3df10c/ipc_proxy_kernel.py
Moving java kernel from /usr/share/jupyter/kernels/java...
Wrote modified kernel.json for java_tcp in /usr/share/jupyter/kernels/java_tcp/kernel.json
Installing the proxy kernel in place of java in /usr/share/jupyter/kernels/java
Installed proxy kernelspec: {"argv": ["/usr/bin/python3", "/usr/share/jupyter/kernels/java/ipc_proxy_kernel.py", "{connection_file}", "--kernel=java_tcp"], "env": {}, "display_name": "Java", "language": "java", "interrupt_mode": "message", "metadata": {}}
Proxy kernel installed. Go to 'Runtime > Change runtime type' and select 'java'

Hola Mundo en Java desde Colab#

System.out.println("Hola mundo en Colab desde Java");
Hola mundo en Colab desde Java

Recordemos que objeto y clase son similares, ¡pero no lo mismo!:#

Clase y objeto son términos que se utilizan en programación orientada a objetos (OOP, por sus siglas en inglés). En este paradigma, una clase es una plantilla para crear objetos que comparten una estructura de datos y un comportamiento común.

Por otro lado, un objeto es una instancia de una clase, es decir, es una representación concreta de una clase con valores específicos para sus atributos y métodos. Cada objeto puede tener valores distintos para los atributos y comportarse de manera diferente según las acciones que se le apliquen.

Definición de clases#

//Definimos la clase
public class Vehicle {
    //Se definen los atributos de la clase
    protected String make;
    protected String model;
    protected int year;

    // Declaramos el constructor de la clase
    public Vehicle(String make, String model, int year) {
        this.make = make;
        this.model = model;
        this.year = year;
    }

    // Métodos de la clase
    public String getDescriptiveName() {
        String longName = year + " " + make + " " + model;
        return longName.toUpperCase();
    }
}
// Instanciar una clase
Vehicle myCar = new Vehicle("bmw", "x5", 2022);
System.out.println(myCar.getDescriptiveName());
2022 BMW X5

Herencia de clases#

// Vamos a crear una clase carro que hereda de la clase vehículo
class Car extends Vehicle {
    public int numDoors;

    public Car(String make, String model, int year, int numDoors) {
        super(make, model, year);
        this.numDoors = numDoors;
    }
      // en caso de que la variable fuera privada y se desea acceder al atributo se necesita los gets a sets
     //public int getNumDoors() {
    //    return numDoors;
    //}
        // Métodos de la clase -- metodo sobrecargado para poder imprimir el numero de puertas
    //@Override
    //public String getDescriptiveName() {
    //    String longName = year + " " + make + " " + model+" "+numDoors;
    //    return longName.toUpperCase();
    //}
}

Car myCar = new Car("bmw", "x5", 2022, 4);
System.out.println(myCar.getDescriptiveName());
2022 BMW X5
myCar.numDoors
4

Polimorfismo#

// Clase Animal
public class Animal {
    protected String name;

    public Animal(String name) {
        this.name = name;
    }

    public void hacerSonido() {
        System.out.println("Haciendo sonido de animal");
    }
}
// Clase Perro que extiende de Animal
public class Perro extends Animal {
    public Perro(String name) {
        super(name);
    }
    @Override
    public void hacerSonido() {
        System.out.println("Guau guau!");
    }
}
// Clase Gato que extiende de Animal
public class Gato extends Animal {
    public Gato(String name) {
        super(name);
    }
    @Override
    public void hacerSonido() {
        System.out.println("Miau miau!");
    }
}
Animal animal1 = new Perro("Fido");
Animal animal2 = new Gato("Pepe");

animal1.hacerSonido(); // Salida: Guau guau!
animal2.hacerSonido(); // Salida: Miau miau!
Haciendo sonido de animal
Miau miau!

Polimorfismo y clases abstractas#

// Definimos una clase padre
abstract class Animal {
    protected String name;

    public Animal(String name) {
        this.name = name;
    }

    public abstract String speak();

}
// Creamos una clase perro y otra gato que hereda los métodos de Animal.
class Dog extends Animal {

    public Dog(String name) {
        super(name);
    }

    // Se modifica el método speak
    @Override
    public String speak() {
        return "Woof!";
    }
}

class Cat extends Animal {

    public Cat(String name) {
        super(name);
    }

    @Override
    public String speak() {
        return "Meow!";
    }
}

public static void petSpeak(Animal pet) {
    System.out.println(pet.speak());
}
// Instanciamos la clase perro
Dog dog = new Dog("Fido");
Cat cat = new Cat("Fluffy");

// Llamamos la función speak para cada objeto
petSpeak(dog);
petSpeak(cat);
Woof!
Meow!

Decoradores#

En java no existe el concepto de decoradores como en Python

Interfaces#

interface Shape {
    double area();
    double perimeter();
}
class Rectangle implements Shape {
    private double width;
    private double height;

    public Rectangle(double width, double height) {
        this.width = width;
        this.height = height;
    }

    @Override
    public double area() {
        return width * height;
    }

    @Override
    public double perimeter() {
        return 2 * (width + height);
    }
}

class Circle implements Shape {
    private double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    @Override
    public double area() {
        return 3.14 * (radius * radius);
    }

    @Override
    public double perimeter() {
        return 2 * 3.14 * radius;
    }
}

En este ejemplo, se define la interfaz Shape con los métodos area() y perimeter(). Luego, se implementan las clases Rectangle y Circle, que implementan la interfaz Shape y proporcionan sus propias implementaciones de los métodos area() y perimeter().

En la implementación de las clases Rectangle y Circle, se utilizan las anotaciones @Override para indicar que se están anulando los métodos de la interfaz Shape.

Rectangle rectangle=new Rectangle(4,3);
rectangle.area()
12.0
rectangle.perimeter()
14.0

Consumo de API’s usando módulos de Java#

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


URL url = new URL("https://pokeapi.co/api/v2/pokemon?limit=151");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");

int status = connection.getResponseCode();
System.out.println(status);

BufferedReader input = new BufferedReader(
        new InputStreamReader(connection.getInputStream())
);
StringBuilder response = new StringBuilder();
String inputLine;
while ((inputLine = input.readLine()) != null) {
    response.append(inputLine);
}
input.close();

System.out.println(response.toString());
200
{"count":1279,"next":"https://pokeapi.co/api/v2/pokemon?offset=151&limit=151","previous":null,"results":[{"name":"bulbasaur","url":"https://pokeapi.co/api/v2/pokemon/1/"},{"name":"ivysaur","url":"https://pokeapi.co/api/v2/pokemon/2/"},{"name":"venusaur","url":"https://pokeapi.co/api/v2/pokemon/3/"},{"name":"charmander","url":"https://pokeapi.co/api/v2/pokemon/4/"},{"name":"charmeleon","url":"https://pokeapi.co/api/v2/pokemon/5/"},{"name":"charizard","url":"https://pokeapi.co/api/v2/pokemon/6/"},{"name":"squirtle","url":"https://pokeapi.co/api/v2/pokemon/7/"},{"name":"wartortle","url":"https://pokeapi.co/api/v2/pokemon/8/"},{"name":"blastoise","url":"https://pokeapi.co/api/v2/pokemon/9/"},{"name":"caterpie","url":"https://pokeapi.co/api/v2/pokemon/10/"},{"name":"metapod","url":"https://pokeapi.co/api/v2/pokemon/11/"},{"name":"butterfree","url":"https://pokeapi.co/api/v2/pokemon/12/"},{"name":"weedle","url":"https://pokeapi.co/api/v2/pokemon/13/"},{"name":"kakuna","url":"https://pokeapi.co/api/v2/pokemon/14/"},{"name":"beedrill","url":"https://pokeapi.co/api/v2/pokemon/15/"},{"name":"pidgey","url":"https://pokeapi.co/api/v2/pokemon/16/"},{"name":"pidgeotto","url":"https://pokeapi.co/api/v2/pokemon/17/"},{"name":"pidgeot","url":"https://pokeapi.co/api/v2/pokemon/18/"},{"name":"rattata","url":"https://pokeapi.co/api/v2/pokemon/19/"},{"name":"raticate","url":"https://pokeapi.co/api/v2/pokemon/20/"},{"name":"spearow","url":"https://pokeapi.co/api/v2/pokemon/21/"},{"name":"fearow","url":"https://pokeapi.co/api/v2/pokemon/22/"},{"name":"ekans","url":"https://pokeapi.co/api/v2/pokemon/23/"},{"name":"arbok","url":"https://pokeapi.co/api/v2/pokemon/24/"},{"name":"pikachu","url":"https://pokeapi.co/api/v2/pokemon/25/"},{"name":"raichu","url":"https://pokeapi.co/api/v2/pokemon/26/"},{"name":"sandshrew","url":"https://pokeapi.co/api/v2/pokemon/27/"},{"name":"sandslash","url":"https://pokeapi.co/api/v2/pokemon/28/"},{"name":"nidoran-f","url":"https://pokeapi.co/api/v2/pokemon/29/"},{"name":"nidorina","url":"https://pokeapi.co/api/v2/pokemon/30/"},{"name":"nidoqueen","url":"https://pokeapi.co/api/v2/pokemon/31/"},{"name":"nidoran-m","url":"https://pokeapi.co/api/v2/pokemon/32/"},{"name":"nidorino","url":"https://pokeapi.co/api/v2/pokemon/33/"},{"name":"nidoking","url":"https://pokeapi.co/api/v2/pokemon/34/"},{"name":"clefairy","url":"https://pokeapi.co/api/v2/pokemon/35/"},{"name":"clefable","url":"https://pokeapi.co/api/v2/pokemon/36/"},{"name":"vulpix","url":"https://pokeapi.co/api/v2/pokemon/37/"},{"name":"ninetales","url":"https://pokeapi.co/api/v2/pokemon/38/"},{"name":"jigglypuff","url":"https://pokeapi.co/api/v2/pokemon/39/"},{"name":"wigglytuff","url":"https://pokeapi.co/api/v2/pokemon/40/"},{"name":"zubat","url":"https://pokeapi.co/api/v2/pokemon/41/"},{"name":"golbat","url":"https://pokeapi.co/api/v2/pokemon/42/"},{"name":"oddish","url":"https://pokeapi.co/api/v2/pokemon/43/"},{"name":"gloom","url":"https://pokeapi.co/api/v2/pokemon/44/"},{"name":"vileplume","url":"https://pokeapi.co/api/v2/pokemon/45/"},{"name":"paras","url":"https://pokeapi.co/api/v2/pokemon/46/"},{"name":"parasect","url":"https://pokeapi.co/api/v2/pokemon/47/"},{"name":"venonat","url":"https://pokeapi.co/api/v2/pokemon/48/"},{"name":"venomoth","url":"https://pokeapi.co/api/v2/pokemon/49/"},{"name":"diglett","url":"https://pokeapi.co/api/v2/pokemon/50/"},{"name":"dugtrio","url":"https://pokeapi.co/api/v2/pokemon/51/"},{"name":"meowth","url":"https://pokeapi.co/api/v2/pokemon/52/"},{"name":"persian","url":"https://pokeapi.co/api/v2/pokemon/53/"},{"name":"psyduck","url":"https://pokeapi.co/api/v2/pokemon/54/"},{"name":"golduck","url":"https://pokeapi.co/api/v2/pokemon/55/"},{"name":"mankey","url":"https://pokeapi.co/api/v2/pokemon/56/"},{"name":"primeape","url":"https://pokeapi.co/api/v2/pokemon/57/"},{"name":"growlithe","url":"https://pokeapi.co/api/v2/pokemon/58/"},{"name":"arcanine","url":"https://pokeapi.co/api/v2/pokemon/59/"},{"name":"poliwag","url":"https://pokeapi.co/api/v2/pokemon/60/"},{"name":"poliwhirl","url":"https://pokeapi.co/api/v2/pokemon/61/"},{"name":"poliwrath","url":"https://pokeapi.co/api/v2/pokemon/62/"},{"name":"abra","url":"https://pokeapi.co/api/v2/pokemon/63/"},{"name":"kadabra","url":"https://pokeapi.co/api/v2/pokemon/64/"},{"name":"alakazam","url":"https://pokeapi.co/api/v2/pokemon/65/"},{"name":"machop","url":"https://pokeapi.co/api/v2/pokemon/66/"},{"name":"machoke","url":"https://pokeapi.co/api/v2/pokemon/67/"},{"name":"machamp","url":"https://pokeapi.co/api/v2/pokemon/68/"},{"name":"bellsprout","url":"https://pokeapi.co/api/v2/pokemon/69/"},{"name":"weepinbell","url":"https://pokeapi.co/api/v2/pokemon/70/"},{"name":"victreebel","url":"https://pokeapi.co/api/v2/pokemon/71/"},{"name":"tentacool","url":"https://pokeapi.co/api/v2/pokemon/72/"},{"name":"tentacruel","url":"https://pokeapi.co/api/v2/pokemon/73/"},{"name":"geodude","url":"https://pokeapi.co/api/v2/pokemon/74/"},{"name":"graveler","url":"https://pokeapi.co/api/v2/pokemon/75/"},{"name":"golem","url":"https://pokeapi.co/api/v2/pokemon/76/"},{"name":"ponyta","url":"https://pokeapi.co/api/v2/pokemon/77/"},{"name":"rapidash","url":"https://pokeapi.co/api/v2/pokemon/78/"},{"name":"slowpoke","url":"https://pokeapi.co/api/v2/pokemon/79/"},{"name":"slowbro","url":"https://pokeapi.co/api/v2/pokemon/80/"},{"name":"magnemite","url":"https://pokeapi.co/api/v2/pokemon/81/"},{"name":"magneton","url":"https://pokeapi.co/api/v2/pokemon/82/"},{"name":"farfetchd","url":"https://pokeapi.co/api/v2/pokemon/83/"},{"name":"doduo","url":"https://pokeapi.co/api/v2/pokemon/84/"},{"name":"dodrio","url":"https://pokeapi.co/api/v2/pokemon/85/"},{"name":"seel","url":"https://pokeapi.co/api/v2/pokemon/86/"},{"name":"dewgong","url":"https://pokeapi.co/api/v2/pokemon/87/"},{"name":"grimer","url":"https://pokeapi.co/api/v2/pokemon/88/"},{"name":"muk","url":"https://pokeapi.co/api/v2/pokemon/89/"},{"name":"shellder","url":"https://pokeapi.co/api/v2/pokemon/90/"},{"name":"cloyster","url":"https://pokeapi.co/api/v2/pokemon/91/"},{"name":"gastly","url":"https://pokeapi.co/api/v2/pokemon/92/"},{"name":"haunter","url":"https://pokeapi.co/api/v2/pokemon/93/"},{"name":"gengar","url":"https://pokeapi.co/api/v2/pokemon/94/"},{"name":"onix","url":"https://pokeapi.co/api/v2/pokemon/95/"},{"name":"drowzee","url":"https://pokeapi.co/api/v2/pokemon/96/"},{"name":"hypno","url":"https://pokeapi.co/api/v2/pokemon/97/"},{"name":"krabby","url":"https://pokeapi.co/api/v2/pokemon/98/"},{"name":"kingler","url":"https://pokeapi.co/api/v2/pokemon/99/"},{"name":"voltorb","url":"https://pokeapi.co/api/v2/pokemon/100/"},{"name":"electrode","url":"https://pokeapi.co/api/v2/pokemon/101/"},{"name":"exeggcute","url":"https://pokeapi.co/api/v2/pokemon/102/"},{"name":"exeggutor","url":"https://pokeapi.co/api/v2/pokemon/103/"},{"name":"cubone","url":"https://pokeapi.co/api/v2/pokemon/104/"},{"name":"marowak","url":"https://pokeapi.co/api/v2/pokemon/105/"},{"name":"hitmonlee","url":"https://pokeapi.co/api/v2/pokemon/106/"},{"name":"hitmonchan","url":"https://pokeapi.co/api/v2/pokemon/107/"},{"name":"lickitung","url":"https://pokeapi.co/api/v2/pokemon/108/"},{"name":"koffing","url":"https://pokeapi.co/api/v2/pokemon/109/"},{"name":"weezing","url":"https://pokeapi.co/api/v2/pokemon/110/"},{"name":"rhyhorn","url":"https://pokeapi.co/api/v2/pokemon/111/"},{"name":"rhydon","url":"https://pokeapi.co/api/v2/pokemon/112/"},{"name":"chansey","url":"https://pokeapi.co/api/v2/pokemon/113/"},{"name":"tangela","url":"https://pokeapi.co/api/v2/pokemon/114/"},{"name":"kangaskhan","url":"https://pokeapi.co/api/v2/pokemon/115/"},{"name":"horsea","url":"https://pokeapi.co/api/v2/pokemon/116/"},{"name":"seadra","url":"https://pokeapi.co/api/v2/pokemon/117/"},{"name":"goldeen","url":"https://pokeapi.co/api/v2/pokemon/118/"},{"name":"seaking","url":"https://pokeapi.co/api/v2/pokemon/119/"},{"name":"staryu","url":"https://pokeapi.co/api/v2/pokemon/120/"},{"name":"starmie","url":"https://pokeapi.co/api/v2/pokemon/121/"},{"name":"mr-mime","url":"https://pokeapi.co/api/v2/pokemon/122/"},{"name":"scyther","url":"https://pokeapi.co/api/v2/pokemon/123/"},{"name":"jynx","url":"https://pokeapi.co/api/v2/pokemon/124/"},{"name":"electabuzz","url":"https://pokeapi.co/api/v2/pokemon/125/"},{"name":"magmar","url":"https://pokeapi.co/api/v2/pokemon/126/"},{"name":"pinsir","url":"https://pokeapi.co/api/v2/pokemon/127/"},{"name":"tauros","url":"https://pokeapi.co/api/v2/pokemon/128/"},{"name":"magikarp","url":"https://pokeapi.co/api/v2/pokemon/129/"},{"name":"gyarados","url":"https://pokeapi.co/api/v2/pokemon/130/"},{"name":"lapras","url":"https://pokeapi.co/api/v2/pokemon/131/"},{"name":"ditto","url":"https://pokeapi.co/api/v2/pokemon/132/"},{"name":"eevee","url":"https://pokeapi.co/api/v2/pokemon/133/"},{"name":"vaporeon","url":"https://pokeapi.co/api/v2/pokemon/134/"},{"name":"jolteon","url":"https://pokeapi.co/api/v2/pokemon/135/"},{"name":"flareon","url":"https://pokeapi.co/api/v2/pokemon/136/"},{"name":"porygon","url":"https://pokeapi.co/api/v2/pokemon/137/"},{"name":"omanyte","url":"https://pokeapi.co/api/v2/pokemon/138/"},{"name":"omastar","url":"https://pokeapi.co/api/v2/pokemon/139/"},{"name":"kabuto","url":"https://pokeapi.co/api/v2/pokemon/140/"},{"name":"kabutops","url":"https://pokeapi.co/api/v2/pokemon/141/"},{"name":"aerodactyl","url":"https://pokeapi.co/api/v2/pokemon/142/"},{"name":"snorlax","url":"https://pokeapi.co/api/v2/pokemon/143/"},{"name":"articuno","url":"https://pokeapi.co/api/v2/pokemon/144/"},{"name":"zapdos","url":"https://pokeapi.co/api/v2/pokemon/145/"},{"name":"moltres","url":"https://pokeapi.co/api/v2/pokemon/146/"},{"name":"dratini","url":"https://pokeapi.co/api/v2/pokemon/147/"},{"name":"dragonair","url":"https://pokeapi.co/api/v2/pokemon/148/"},{"name":"dragonite","url":"https://pokeapi.co/api/v2/pokemon/149/"},{"name":"mewtwo","url":"https://pokeapi.co/api/v2/pokemon/150/"},{"name":"mew","url":"https://pokeapi.co/api/v2/pokemon/151/"}]}