将 switch 与子类一起使用?

发布于 2024-11-01 10:36:12 字数 254 浏览 1 评论 0原文

是否可以使用 switch 并在不同情况下具有不同的子类?我想使用 switch 而不是几个 if 语句。我有一个名为指令的抽象类和具有不同类型的子类。所以我希望每个案例都是不同的子类。喜欢:

switch (instruction){
    case instruction1:
    case instruction2:
    case instruction3:
}

等等 如前所述,指令1、2、3是同一类的子类。

Is it possible to use switch and having as cases different subclasses ? I want to use switch instead of several if statements. I have an abstract class called instruction and subclasses with different types. So i want each case to be a different subclass. like :

switch (instruction){
    case instruction1:
    case instruction2:
    case instruction3:
}

etc
as said instruction1,2,3 are subclasses of same class.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

驱逐舰岛风号 2024-11-08 10:36:12

不,switch 仅适用于数值和枚举。 (在 Java 7 中,它也适用于字符串。)

听起来您可能应该在不同的子类中重写一个方法...或者可能使用枚举(它仍然可以重写方法)。

如果这没有帮助,请提供有关您正在尝试执行的操作的更多信息 - 最好有一个示例。

No, switch only works on numeric values and enums. (In Java 7 it will work on strings too.)

It sounds like you should probably have a method overridden in the different subclasses... or possibly use enums (which can still override methosds).

If that doesn't help, please give more information about what you're trying to do - ideally with an example.

看透却不说透 2024-11-08 10:36:12

看起来您想改用运行时多态性。

只需调用对象的方法并在每个子类中以不同的方式实现它即可。

It looks like you'd want to use runtime polymorphism instead.

Simply call a method on the object and implement it differently in each subclass.

隐诗 2024-11-08 10:36:12

另一种可能性(有点黑客)是在超类中创建一个枚举,并创建一个抽象方法 getEnum() ,该方法将由每个子类实现。然后,每个子类都会返回一个不同的枚举实例。如:

abstract class Super
{
enum Type {ONE, TWO, THREE};

abstract Type getType();
}

public class ChildOne extends Super
{
public Type getType()
{
return Type.ONE;
}
}

public class ChildTwo extends Super
{
public Type getType()
{
return Type.TWO;
}
}

那么你可以这样做:

Super someClass;
switch(someClass.getType())
{
case ONE:
//domSomething
break;

case TWO:
//domSomeOtherThin
break;
//...
}

Another possibility (somewhat of a hack) would be to create an enum in the superclass and an abstract method getEnum() which would be implemented by each subclass. The subclasses would then each return a different instance for the enum. As in:

abstract class Super
{
enum Type {ONE, TWO, THREE};

abstract Type getType();
}

public class ChildOne extends Super
{
public Type getType()
{
return Type.ONE;
}
}

public class ChildTwo extends Super
{
public Type getType()
{
return Type.TWO;
}
}

Then you could do:

Super someClass;
switch(someClass.getType())
{
case ONE:
//domSomething
break;

case TWO:
//domSomeOtherThin
break;
//...
}
花心好男孩 2024-11-08 10:36:12

不可以,在 Java 中,您只能使用整数作为切换条件(编辑:和 enum,其中使用 ordinal())。您正在寻找的解决方案(而不是带有大量 instanceof 运算符的令人讨厌的 if-else)是 访客模式

No, in Java you can only use integers as switch conditions (edit: and enums where ordinal() is used). The solution you are looking for (instead of nasty if-else with plenty of instanceof operators) is the Visitor pattern.

柒夜笙歌凉 2024-11-08 10:36:12

扩展 Jon 的回答:在 Java 中,枚举是对象,因此您可能能够通过使用枚举来实现您想要做的事情,具体取决于枚举是什么。也就是说,这可能不是一个非常优雅的方法。

Expanding on Jon's response: in Java enums are objects, so you might be able to achieve what you're trying to do by using enums, depending on exactly what that is. That said, it's likely to be not a very elegant approach.

追我者格杀勿论 2024-11-08 10:36:12

根据您想要实现的目标,使用 if-statementsSuperclass.isAssignableFrom(Subclass)Subclass.isAssignableFrom(SuperClass) 作为条件。可能是您希望通过 switch 语句 实现的目标的良好替代品。

或者使用 instanceof 运算符代替 isAssignableFrom() 函数。

Using if-statements with Superclass.isAssignableFrom(Subclass) or Subclass.isAssignableFrom(SuperClass) as a condition depending on what you want to achieve. Might be a good substitute for what you're looking to achieve with switch statements.

Or alternatively use instanceof operators instead of the isAssignableFrom() function.

若水微香 2024-11-08 10:36:12

您可能会很高兴知道我们有 Switch 的模式匹配功能
开关表达式 - 类型模式:https://openjdk.org/jeps/441

// from Java 17 as preview & from Java 21 as stable

static String formatterPatternSwitch(Object obj) {
    return switch (obj) {
        case Integer i -> String.format("int %d", i);
        case Long l    -> String.format("long %d", l);
        case Double d  -> String.format("double %f", d);
        case String s  -> String.format("String %s", s);
        default        -> obj.toString();
    };
}

You'd probably be happy to know we know have Pattern Matching for Switch
Switch Expressions - Type Patterns
: https://openjdk.org/jeps/441

// from Java 17 as preview & from Java 21 as stable

static String formatterPatternSwitch(Object obj) {
    return switch (obj) {
        case Integer i -> String.format("int %d", i);
        case Long l    -> String.format("long %d", l);
        case Double d  -> String.format("double %f", d);
        case String s  -> String.format("String %s", s);
        default        -> obj.toString();
    };
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文