java polymorphism

Using a child class as a parent class

An important aspect of polymorphism is the ability to use an object of a child class where an object of its parent class is expected. One way to do this explicitly is to create an instance of the child class object as a member of the parent class.

Now the question is

Why

Noodle biangBiang = new Spaghetti();

If we can write and the result is one and the same

Spaghetti biangBiang = new Spaghetti();

Example of the entire code

class Noodle {

  protected double lengthInCentimeters;
  protected double widthInCentimeters;
  protected String shape;
  protected String ingredients;
  protected String texture = "brittle";

  Noodle(double lenInCent, double wthInCent, String shp, String ingr) {

    this.lengthInCentimeters = lenInCent;
    this.widthInCentimeters = wthInCent;
    this.shape = shp;
    this.ingredients = ingr;

  }

  public String getCookPrep() {

    return "Boil noodle for 7 minutes and add sauce.";

  }

  public static void main(String[] args) {
    Noodle n = new Noodle(30.0, 0.2, "round", "semolina flour");
    System.out.println(n.getCookPrep());
    Spaghetti a = new Spaghetti();
    System.out.println(a.getCookPrep());


  }

}

class Spaghetti extends Noodle {

  Spaghetti() {

    super(30.0, 0.2, "round", "semolina flour");

  }

  public String getCookPrep() {

    return "Boil spaghetti for 8 - 12 minutes and add sauce, cheese, or oil and garlic.";

  }

}

Explain the principle of polymorphism, I kind of understood it, but apparently not with all the times I ask this question, and preferably an example, and a good article and a task on the topic of polymorphism. Thanks.

Author: FCAndroidFC, 2019-09-04

2 answers

For example, for this

public static void main(String[] args) {
    Noodle n = new Noodle(30.0, 0.2, "round", "semolina flour");        
    Spaghetti a = new Spaghetti();        

    printCookPrep(n);
    printCookPrep(a);
}

public static void printCookPrep(Noodle n){
    System.out.println(n.getCookPrep());
}
 8
Author: tym32167, 2019-09-04 21:31:12

For example, you have a database of company employees. It has an abstract "Employee" class (which has the name and salary fields, as well as access methods to them), and inherits from it more specific "Manager"," Programmer"," Cleaner", etc., which have their own more specific states and behaviors.

And here is the task: to display a list of all employees and their salary in one file.

For abstract classes, you can create object variables, but such variables must refer to an object of a non-abstract class. If you collect all the employees in the list in advance, then this task will be solved in one crawl of the collection.

public abstract class Employee {
    private String name;
    private Integer pay;

    public void setName(String aName) {
        name = aName;
    }

    public String getName() {
        return name;
    }

    public void setPay(int value) {
        pay = value;
    }

    public Integer getPay() {
        return pay;
    }
}

public class Coder extends Employee {
    private String position;

    public Coder(String name, int pay, String _position) {
        setName(name);
        setPay(pay);
        setPosition(_position);
    }

    public void setPosition(String value) {
        position = value;
    }

    public String getPosition() {
        return position;
    }
}


public class Manager extends Employee {
    public Manager(String name, int pay) {
        setName(name);
        setPay(pay);
    } 
}

public class TEST {

    public static void main(String[] args) {
        LinkedList<Employee> employees = new LinkedList<Employee>();
        // Нанимаем менеджера
        employees.add(new Manager("John", 25000));
        // Нанимаем программиста
        Coder coder1 = new Coder("Nick", 30000, "Junior");
        employees.add(coder1);
        // Нанимаем ещё менеджера
        Manager manager1 = new Manager("Cameron", 25000);
        employees.add(manager1);
        // Выводим список всех сотрудников
        for (Employee current : employees) {
            System.out.println(current.getName() + " - " + current.getPay().toString());
        }
    }
}

Here is an example of implementing the principle of polymorphism, objects of a subclass can be accessed from the reference variables of their superclass. BUT here, for example, it will not be possible to call the setPosition method from the collection for an object of the Coder class, since the Employee class has no information about it concepts.

employees.get(1).setPosition("Middle"); //error: cannot find symbol

// правильное решение, однако для этого необходимо проверять, является ли данный объект коллекции объектом требуемого класса, например используя instanceof
Coder myCoder = employees.get(1);
myCoder.setPosition("Middle");

I can recommend the book by Kay Horstmann "Java Professorial Library" volume 1. The chapter on "Inheritance" explains this in more detail and with code examples.

 4
Author: dedkot, 2019-09-05 05:56:41