Auxiliary Massive. How do you get an altercation from your daughter?



  • A list class has been established from the abstract class:

    public class List {
        protected ArrayList <Transport> transports = new ArrayList();
    }
    

    Abstract class:

    public abstract class Transport {
        protected String model;
        protected int price;
        protected int maxSpeed;
    }
    

    On the list, I can turn to a variable abstract class:

    for (Transport transport: transports) {
        if(transport.price < 30000) {
            transport.print();
        }
    }
    

    There is a subsidiary class created by the abstract with its variables:

    public class Car extends Transport {
        protected static String type = "Машина";
        protected int fuel;
        protected int fuel100km;
    }
    

    So the question is, is there any way we can use the list to the variable subsidiary class?


  • QA Engineer

    1. Title List It's obviously not a good one, because it matches the name of the interface. List package java.utilwhich could lead to confusion/consciousness.
    2. In itself, the problem of the treatment from the pre-primary class directly to the fields of grades is a bad smell code (code smell) because the class of ancestors should not Depending on the characteristics of / methods defined in the flux classes.

    Adjustable solution: to define in the base class some abstract/virtual method that should be redefined in descendants depending on their implementation, and to use the necessary fields of descendants in such method/methods.

    public abstract class Transport {
        protected abstract boolean isOk();
    
    public void foo() {
        for (Transport transport: transports) {
            if (transport.price &lt; 30000 &amp;&amp; transport.isOk()) {
                transport.print();
            }
        }    
    }
    public void print() {
        // печатать поля класса-предка
    }
    

    }

    public class Car extends Transport {
    @Override
    protected boolean isOk() {
    return this.fuel > 10;
    }

    @Override
    public void print() { 
        super.print(); // напечатать поля класса-предка
        // напечатать поля данного класса-потомка
    }
    

    }


    NECORRETEC method: check the specific type of class and result in the type of class to challenge its methods/fields.

    public class Transport {
    public void foo() {
    for (Transport transport: transports) {
    if (transport.price < 30000) {
    // так НЕ НАДО делать
    if (transport instanceof Car) {
    Car car = (Car) transport;
    car.fuel += 100500;
    }
    }
    }
    }
    }



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2