简体   繁体   English

Java Enum在switch语句上

[英]Java Enum on a switch statement

I have this piece of code right here , I really don't get it why is that there is a "this" keyword in the switch statement, take a look at this code 我在这里有这段代码,我真的不明白为什么在switch语句中有一个“ this”关键字,请看一下这段代码

public enum InstrumentType{

    GUITAR,BANJO,MANDOLIN,DOBRO, FIDDLE ,BASS,

    public String toString(){
        switch(this){
        case GUITAR:
            return "Guitar";
        case BANJO: 
            return "Banjo";
        case DOBRO:
            return "Dobro";
        case FIDDLE:
            return "Fiddle";
        case BASS:
            return "Bass";
        case MANDOLIN:
            return "Mandolin";
        default: 
            return "Unspecified";
        }
    }
}

Here this refers to the current InstrumentType value 这里是指当前InstrumentType

static void MyFunc( )
{
    InstrumentType f = InstrumentType.GUITAR;
    String s = f.toString();
}

When f.toString() is invoked. 调用f.toString() this will have GUITAR value 将具有GUITAR价值

It refers to the current instance. 它引用当前实例。

If you had an anum instance "foo": 如果您有一个anum实例“ foo”:

String s = foo.toString();

this points to its container class/struct/enum like elements. this指向它的容器类/结构/枚举之类的元素。 in this case, this is used for InstrumentType . 在这种情况下, this用于InstrumentType it's a basic rule for most of the OO languages. 这是大多数OO语言的基本规则。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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