I've been testing out generic programming in Java.
Here is a snippet of my code:
public class Vehicle<T extends Style> {
private T make;
private String color;
private int year;
private String brand;
private String model;
public Vehicle() {
this.brand = make.getMake();
}
public Vehicle(String c, int yr, String mod) {
this.brand = make.getMake();
this.color = c;
this.year = yr;
this.model = mod;
}
public void printInfo() {
System.out.println(this.year + " " + this.color + " " + this.brand + " " + this.model);
}
public void setColor(String c) {
this.color = c;
}
public void setYear(int yr) {
this.year = yr;
}
public void setModel(String mod) {
this.model = mod;
}
}
And here is the interface Style
that is being extended in the type parameter:
public interface Style {
public String getMake();
public boolean usesGas();
public boolean usesElectricity();
}
This interface is implement by another class called Ford
, where the getMake()
method is implement like so:
private String make = "FORD";
public String getMake() {
return make;
}
In my driver class Test
, I am testing all of these things like so:
public class Test{
public static void main(String[] args){
Vehicle<Ford> fordFusion = new Vehicle<Ford>();
fordFusion.setColor("GRAY");
fordFusion.setModel("FUSION");
fordFusion.setYear(2015);
fordFusion.printInfo();
}
}
Now, in my understanding, one should be able to access the field variables and methods of a generic object by using an interface, which in this case is my Style
interface. And the compiler has no problems with this in the IDE. The program should be accessing the getMake()
method and printing out:
2015 GRAY FORD FUSION
However, the console shows:
Exception in thread "main" java.lang.NullPointerException
at Vehicle.<init>(Vehicle.java:32)
at Test.main(Driver.java:16)
which points to the line where I have this.brand = make.getMake();
So what in the world is going on here? What am I doing wrong?
EDIT: The question that this has been marked a duplicate of does not give a solution to my particular situation. Although the error here is a NullPointerException
, it is much different than that older question.
Here is a question that address the same issue as mine. If the solution to that question is valid, then I should be able to accomplish what I've been trying to do.