简体   繁体   中英

using getters and setters with enum class java

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;
    }
}

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM