Как вернуть интерфейсный объект? - PullRequest
0 голосов
/ 02 февраля 2020

У меня есть интерфейс Транспорт и 2 класса Автомобили и Мото. Я пишу в файле все детали о каком-то автомобиле или мото. Как я могу написать метод public static Transport inputTransport(InputStream in)? У меня нет никакой информации в файле о типе класса (Автомобиль или Мото). Должен ли я записать эту информацию в файл, а после этого создать новый автомобиль или мотоцикл и вернуть его, или я могу написать что-то еще?

public interface Transport {
    public void addModel(String model, double price) throws DuplicateModelNameException;
    public void deleteModel(String model) throws NoSuchModelNameException;
    public void changeModel(String model, String new_model) throws NoSuchModelNameException,DuplicateModelNameException;
    public void changePrice(String model, double new_price) throws NoSuchModelNameException;
    public void changeType(String type);
    public String getType();
    public int getNumber();
    public String getPrice(String model) throws NoSuchModelNameException;
    public String[] getAllModels();
    public double[] getAllPrices();
} 
class Cars implements Transport{

    private String type;
    private Models[] cars;
    private int number;

    Cars(String type, int number){
        this.type = type;
        this.number = number;
        cars = new Models[number];
        for (int i = 0; i < number; i++){
            cars[i] = new Models("default", Double.NaN);
        }
    } ...

class Motos implements Transport {
    private int count = 0;
    private String type;

    Motos(String type){
        this.type = type;
    }...

1 Ответ

0 голосов
/ 02 февраля 2020

Вы можете использовать ObjectOutputStream и сохранить ваши объекты в файл, затем вы используете ObjectInputStream для импорта объектов, и этот InputStream теперь будет точным классом вашего объекта.

Я написал небольшую примерную Программу, которая должен начать.

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class Main {
    public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
        A a = new A();
        B b = new B();

        save(a);

        C c = load();

        System.out.println(c.getClass()); // prints "A"

        if (c instanceof A) {
            System.out.println("is of class A");
            A loaded = (A) c;// you can now use this object
            System.out.println(a.someMethod());
        } else if (c instanceof B) {
            System.out.println("is of class B");
            B loaded = (B) c;
        } else {
            System.out.println("should not occur");
        }
    }

    private static C load() throws IOException, FileNotFoundException, ClassNotFoundException {
        ObjectInputStream in = new ObjectInputStream(new FileInputStream("f.txt"));
        C s = (C) in.readObject();
        in.close();
        return s;
    }

    private static void save(C c) throws FileNotFoundException, IOException {
        final FileOutputStream fout = new FileOutputStream("f.txt");
        final ObjectOutputStream out = new ObjectOutputStream(fout);
        out.writeObject(c);
        out.flush();
        out.close();
    }

}

class A implements C {
    // serialVersion is the version of the clas, so if you save the object with
    // serialVersion 1 and then change something, change this version to two, so you
    // get an error if you are trying to load "obsolete" objects
    private static final long serialVersionUID = 1L;

    @Override
    public String getName() {
        return "A";
    }

    public String someMethod() {
        return "someMethod";
    }
}

class B implements C {
    private static final long serialVersionUID = 1L;

    @Override
    public String getName() {
        return "B";
    }

    public String someOtherMethod() {
        return "someOtherMethod";
    }
}

interface C extends Serializable { //Objects saved to a File have to be Serializable
    String getName();
}
...