Orientado a objetos II

Interface (Interface)

Interfaces nos permite especificar una lista de metodos el cual luego una clase puede implementar, las interfaces podemos definirla utilizando la palabra reservada interface. Con las interfaces podemos solo definir metodos sin el contenido que luego podemos ampliar a clases descendiente. Los metodos dentro de interfaces por defecto son metodos abstractos.

  • Book.java
class Book {
  private String isbn;
  private String title;
  private String author;
  private int available;

  public Book(
    String isbn, 
    String title, 
    String author, 
    int available) {
      this.isbn = isbn;
      this.title = title;
      this.author = author;
      this.available = available;
  }

  public boolean getCopy() {
    if(this.available < 1) {
      return false;
    }
    else {
      this.available --;
      return true;
    }
  }

  public String getIsbn() {
    return this.isbn;
  }

  public String getTitle() {
    return this.title;
  }

  public int isAvailable() {
    return this.available;
  }

  public void addCopy() {
    this.available++;
  }
}
  • Person.java
class Person {
  protected static int lastId = 0;
  protected int id;
  protected String firstName;
  protected String lastName;
  protected String email;

  public String getFirstName() {
    return this.firstName;
  }

  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }

  public String getLastName() {
    return this.lastName;
  }

  public void setLastName(String lastName) {
    this.lastName = lastName;
  }

  public static int getLastId() {
    return lastId;
  }

  public int getId() {
   return this.id; 
  }

  public String getEmail() {
    return this.email;
  }

  public void setEmail(String email) {
    this.email = email;
  }

  public String getFullName() {
    return this.firstName + " " + this.lastName;
  }
}
  • Payer.java
interface Payer {
  public void pay(double amount);
  public boolean isExtentOfTaxes();
}
  • Customer.java
interface Customer extends Payer {
  public double getMonthlyFee();
  public int getAmountToBorrow();
  public String getType();
}
  • Basic.java
import java.util.Optional;

class Basic extends Person implements Customer {
  public Basic(
    int id,
    String firstName,
    String lastName,
    String email) {
      if(Optional.ofNullable(id).orElse(0).intValue() == 0) {
        lastId++;
        this.id = lastId;
      }
      else {
        this.id = id;
        if(id > lastId) {
          lastId = id;
        }
      }
      this.firstName = firstName;
      this.lastName = lastName;
      this.email = email;
  }

  public double getMonthlyFee() {
    return 5.0;
  }

  public int getAmountToBorrow() {
    return 3;
  }

  public String getType() {
    return "Basic";
  }

  public void pay(double amount) {
    System.out.println("Paying $" + amount);
  }

  public boolean isExtentOfTaxes() {
    return false;
  }
}
  • Premium.java
import java.util.Optional;

class Premium extends Person implements Customer {
  public Premium(
    int id,
    String firstName,
    String lastName,
    String email) {
      if(Optional.ofNullable(id).orElse(0).intValue() == 0) {
        lastId++;
        this.id = lastId;
      }
      else {
        this.id = id;
        if(id > lastId) {
          lastId = id;
        }
      }
      this.firstName = firstName;
      this.lastName = lastName;
      this.email = email;
  }

  public double getMonthlyFee() {
    return 10.0;
  }

  public int getAmountToBorrow() {
    return 10;
  }

  public String getType() {
    return "Premium";
  }

  public void pay(double amount) {
    System.out.println("Paying $" + amount);
  }

  public boolean isExtentOfTaxes() {
    return true;
  }
}
  • Main.java
class Main {

  public String checkIfValid(Customer customer, Book[] books) {
    String valid = (customer.getAmountToBorrow() >= books.length) 
      ? "Yes you can!"
      : "No you cannot!";
    return valid;
  }

  public String checkIfExtentOfTaxes(Customer customer) {
    String valid = (customer.isExtentOfTaxes()) 
      ? "Yes are extent of taxes!"
      : "No are not extent of taxes!";
    return valid;
  }

  public static void main(String[] args) {
    // Define self
    Main self = new Main();

    // Define books
    Book[] booksList1 = new Book[6];
    booksList1[0] = new Book("9785267006323", "Ready Player One", "Ernest Cline", 10);
    booksList1[1] = new Book("9785267006322", "The Sun and Her Flowers", "Rupi Kaur", 10);
    booksList1[2] = new Book("9785267896322", "The Secret Lives of Color", "Kassia St Clair", 10);
    booksList1[3] = new Book("9785234606321", "Don't Make Me Think", "Steve Krug", 10);
    booksList1[4] = new Book("9734967006324", "Clean Architecture", "Robert Martin", 10);
    booksList1[5] = new Book("9757817006329", "Modular Web Design", "Nathan Curtis", 10);

    Book[] booksList2 = new Book[2];
    booksList1[0] = new Book("9785267006323", "Ready Player One", "Ernest Cline", 10);
    booksList1[1] = new Book("9785267006322", "The Sun and Her Flowers", "Rupi Kaur", 10);

    // Define customer
       Customer customer1 = new Basic(5, "John", "Doe", "[email protected]");
    String validCustomer1 = self.checkIfValid(customer1, booksList1);
    System.out.println(validCustomer1);
    //-> No you cannot!

    Customer customer2 = new Premium(6, "Steve", "Rhills", "[email protected]");
    String validCustomer2 = self.checkIfValid(customer2, booksList1);
    System.out.println(validCustomer2);
    //-> Yes you can!

    Customer customer3 = new Premium(7, "Mary", "Nath", "[email protected]");
    String validCustomer3 = self.checkIfValid(customer3, booksList2);
    System.out.println(validCustomer3);
    //-> Yes you can!

    String payTaxes1 = self.checkIfExtentOfTaxes(customer3);
    System.out.println(payTaxes1);
    //-> Yes are extent of taxes!

    String payTaxes2 = self.checkIfExtentOfTaxes(customer1);
    System.out.println(payTaxes2);
    //-> No are not extent of taxes!

    customer1.pay(20.00);
    //-> Paying $20.0
  }
}

Polimorfismo (Polymorphism)

Es la capacidad que tiene un objeto de tener las mismas propiedades y metodos de la clase padre. Tambien se le puede añadir que los metodos adquiridos por clases padres pueden tener diferentes formas o acciones. Dentro de Java existen dos tipos de polimorfismos.

  • Polimorfismo estatico

Esta polimorfismo es logrado mediante sobrecarga de metodos (method overloading).

  • Calculate.java
class Calculate {
  public int addNumbers(int a, int b) { 
    return a + b;
  }

  public int addNumbers(int a, int b, int c) {
    return a + b + c;
  }
}
  • Main.java
class Main {
  public static void main(String[] args) {
    Calculate calculate = new Calculate();

    // Used method 2
    System.out.println(calculate.addNumbers(3,6,12));  
    //-> 21

    // Used method 1
    System.out.println(calculate.addNumbers(4,5));   
    //-> 9
  }
}
  • Polimorfismo dinamico

Esta polimorfismo es logrado mediante anulacion de metodos (method overriding) simplemente reemplazar un método pariente de una clase por una nueva en la clase descendiente.

  • Pops.java
class Pops {
  public int age = 30;

  public void sayHi() {
    System.out.println("Hi, I am pops.");
  }
}
  • Child.java
class Child extends Pops {
  public int age = 7;

  public void sayHi() {
    System.out.println("Hi, I am child my age is " + age + " year olds. My Pops ages is " + super.age + ".");
  }
}
  • Main.java
class Main {
  public static void main(String[] args) {
    Pops pops = new Pops();
    Child child = new Child();

    pops.sayHi();
    //-> Hi, I am pops.

    child.sayHi();
    //-> Hi, I am child my age is 7 year olds. My Pops ages is 30.
  }
}

results matching ""

    No results matching ""