Issue
If I don't declare private Type type;
and try using getters and setters I'm always getting some kind of error which, of-course, I don't really understand. It's just a red line for me.
I am just trying to understand why I have to declare a separate variable that I didn't think I needed in order to do this.
Please do ask if I'm missing any information. This is my first question ever!
Below is part of the practice exercise that I'm trying to do:
Postgraduate.java that contains extra private data members:
- type: is an Enum called Type, including Research and Coursework;
Implement Java methods in the file Postgraduate.java that include:
- Initialization constructor that assigns values to all data members;
- Public access methods
getType()
that return values of private data members; - Public update methods
setType(Type newType)
that update values of private data members; - Public overriding method
toString()
that returns of postgraduate information.
public class Postgraduate {
private enum Type{Reserch,Coursework;}
private Type type;
public Postgraduate(Type newtype) {
Type type=newtype;
}
public Type getType() {
return type;
}
public void setType(Type newType){
type = newType;
}
}
Solution
An enum is a type, the same as a class or an interface is. Hence this line of your code is declaring a type and not a variable:
private enum Type{Reserch,Coursework;}
This line of your code declares a member variable and not a global variable (as you stated in your comment to your question):
private Type type;
Also, as @ArunGowda wrote in his comment, you have an error in the code of Postgraduate
class constructor. The code should be:
public Postgraduate(Type newtype) {
type = newtype;
}
By convention enum values are written all upper-case. You also spelt Research wrong. Consider the following code:
public class Postgraduate {
private enum Type {RESEARCH, COURSEWORK}
private Type type;
public Postgraduate(Type type) {
this.type = type;
}
@Override // java.lang.Object
public String toString() {
return type.toString();
}
public static void main(String[] args) {
Postgraduate phD = new Postgraduate(Type.RESEARCH);
System.out.println(phD);
}
}
Answered By - Abra
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)