繁体   English   中英

从超类调用子类方法

[英]Calling subclass method from super class

只是想知道我是否能得到一些帮助。

我正在尝试调用以下方法:

 public void updateBrand(Scanner input){
    System.out.println("1 - HIGHSTREET\n2 - FRENCHCONNECTION\n3 - TEDBAKER\nSelect type of brand (Enter number)");
    int choice = input.nextInt();
    switch (choice) {
    case (1):
        setBrand(Brand.highstreet);
        System.out.println("Brand of has been changed to HIGHSTREET");
        break;
    case (2):
        setBrand(Brand.frenchconnection);
        System.out.println("Brand of has been changed to FRENCHCONNECTION");
        break;
    case (3):
        setBrand(Brand.tedbaker);
        System.out.println("Brand of has been changed to TEDBAKER");
        break;
    default: System.out.println("Invalid input");
        break;
    }

   }

从我的MorningSuit子类到我的Suit Super类中的方法:

    public void makeChange(Scanner input){
    System.out.println("Are you sure you want to change this suit? (y or   n)");
    String choice;
    choice = input.next();
    if (choice.toLowerCase() == "y") {
        updateBrand(input);
    }
    else if (choice.toLowerCase() == "n") {
        System.exit(0);
    }
    else {
        System.out.println("Invalid Input");
    }
}

但是当我尝试在我的超级类中调用updateBrand(input)方法时收到错误,因为它不存在。 我该如何解决?

您不能在超类的子类中调用方法。

毕竟,如果实例实际上是另一个子类,该怎么办?

您应该将这两个方法都移到同一类中。

暂无
暂无

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

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