Sobreescribir un método; @override, protected y super
En este tutorial vamos a continuar con el ejemplo del hotel de perros que hemos estado haciendo en los anteriores tutoriales, para explicar las palabras "override, protected y super".
Vamos a utilizar la misma clase main (ahora llamada Tutorial14):
package com.edu4java.tutorial14; public class Tutorial14 { public static void main(String[] args) { Dog2[] dogs = insertDog(); printDogsOnConsole(dogs); feed(dogs); System.out.println("After eating------------"); printDogsOnConsole(dogs); } private static void feed(Dog2[] dogs) { for (int i = 0; i < dogs.length; i++) { double weightBeforefeeding = dogs[i].getWeight(); dogs[i].setWeight(weightBeforefeeding + dogs[i].getPortion()); } } private static void printDogsOnConsole(Dog2[] dogs) { for (int i = 0; i < dogs.length; i++) { dogs[i].printToConsole(); } } private static Dog2[] insertDog() { Dog2[] dogs = new Dog2[4]; // list of Dogs String[] names = { "Coco", "Sultan", "Boby", "Drak" }; String[] colours = { "brown", "black", "white", "blue" }; double[] weight = { 1.5, 75, 3.5, 45.1 }; double[] portion = { 0.2, 1, 0.2, 0.8 }; for (int i = 0; i < dogs.length; i++) { Dog2 dog = new Dog2(); dog.setName(names[i]); dog.setColour(colours[i]); dog.setWeight(weight[i]); dog.setPortion(portion[i]); dogs[i] = dog; } return dogs; } }
En la clase Dog, introduciremos el concepto de protected, haciendo que la variable colour sea accesible desde la clase hija Dog2.
package com.edu4java.tutorial14; /** * A class is a mould from which we can create objects or instances * An object is an instance of a class * * JavaBeans are reusable software components for Java * that can be manipulated visually in a builder tool. */ public class Dog { // instance variables private String name; private double weight; protected String colour; public String getName() { return name; } public void setName(String name) { this.name = name; } public double getWeight() { return weight; } public void setWeight(double weight) { this.weight = weight; } public String getColour() { return colour; } public void setColour(String colour) { this.colour = colour; } public void printToConsole() { System.out.print(" name: " + getName()); System.out.print(" colour: " + this.colour); System.out.println(" weight: " + this.weight); } }
En la clase Dog2 conseguimos imprimir la variable "portion" sin tener que modificar la clase Dog, sobreescribiendo el método printOnConsole.
package com.edu4java.tutorial14; public class Dog2 extends Dog { private double portion; public double getPortion() { return portion; } public void setPortion(double portion) { this.portion = portion; } @Override public void printToConsole() { super.printToConsole(); System.out.println(" portion: " + this.portion); } }
<< Anterior | Siguiente >> |