Question for Java folks, before my sanity gives out. I'm new to programming and have hit a brick wall when trying to code across multiple classes. Basically I want to start with just having 1 or 2 member variables for class Alpha, then building on that in class Beta by adding more member variables, then for class Gamma adding more variables (and also a collection of Beta objects), and so on, building up each time. All the classes are in the same package.
I've put the problem in the most basic code I can:
Code:
public class Alpha {
private String letters;
public Alpha(String letters)
{
this.letters = letters;
}
public String toString()
{
return letters;
}
public static void main(String[] args) {
Alpha test = new Alpha("this is a test");
System.out.println(test);
}
}
Output: this is a test. All fine.
Code:
public class Beta {
private String moreLetters;
private Alpha useOtherClass;
public Beta (String moreLetters, Alpha useOtherClass)
{
this.moreLetters = moreLetters;
this.useOtherClass = useOtherClass;
}
@Override //removing this override makes no difference
public String toString()
{
return moreLetters + useOtherClass;
}
public static void main(String[] args) {
Beta test = new Beta("this is a test", "this is also a test"); //this is what it doesn't like
System.out.println(test);
}
}
The error I get is "incompatible types; String cannot be converted to Alpha". I've seen this or a similar error message (e.g.
int cannot be converted to Beta) a lot at different parts of the code when I've tried different things, but I can't figure out how to get around it, even with a shit ton of google searching/reading.
I can make the error disappear by removing
Alpha useOtherClass and
this.useOtherClass = useOtherClass; from the constructor in Beta, and then removing the offending
"this is also a test". But I don't think that's right because I don't then think I'm adding anything from Beta to Alpha.
Not sure whether adding
public Alpha(){} in Alpha and then changing line 3 of Beta to
private Alpha useOtherClass = new Alpha(); is along the right lines.
Apologies if I've worded this badly or overlooked something basic. Thanks to anyone who helps out.