0

I have a task: Create abstract class Product, then create two inheritant abstract classes MilkProduct and MeatProduct and their inheritants (Milk, Meat, Kefir, Sausage) and output them in descending order by their codes.

public abstract class Product {
protected String name;
protected int code;

public Product() {}
public Product(String name, int code) {
    this.name = name;
    this.code = code;
}

public abstract void input();
public String toString() {
    return "{Name : " + name
            + ";" + "Code: "
            + code + "}";
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public int getCode() {
    return code;
}

public void setCode(int code) {
    this.code = code;
}
}


import java.util.Arrays;
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
    Product[] arr = new Product[10];
    Scanner in = new Scanner(System.in);

    for (int i=0;i<arr.length;i++) {
        arr[i].input();
        if (arr[i].name == "Milk") {
            arr[i] = new Milk(arr[i].name, arr[i].code);
        }
        else if (arr[i].name == "Kolbasa") {
            arr[i] = new Kolbasa(arr[i].name, arr[i].code);
        }
        else if (arr[i].name == "Meat") {
            arr[i] = new Meat(arr[i].name, arr[i].code);
        }
        else if (arr[i].name == "Kefir") {
            arr[i] = new Kefir(arr[i].name, arr[i].code);
        }
    }

    Arrays.sort(arr);
    for (Product e: arr) {
        e.toString();
    }
}
}

and i got an error

Exception in thread "main" java.lang.NullPointerException at HWvirtual.Program.main(Program.java:11)

Andreas
  • 5,393
  • 9
  • 44
  • 53
  • 2
    Does this answer your question? [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Amongalen May 06 '20 at 09:11
  • 1
    Also see: https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java – cegredev May 06 '20 at 09:12
  • `arr[i].input();` In each iteration you call this because you actually initialize i-th element of an array, it is always null. – Amongalen May 06 '20 at 09:13

0 Answers0