简体   繁体   English

调用子类方法而不调用父类

[英]call child class method without call parent class

I want to call this function without using its parent name: 我想在不使用其父名称的情况下调用此函数:

Square square = new Square(Color.Blue, Pattern.DOTTED, 4);

but its error and said use this: 但是它的错误并说使用这个:

Square square = new Square(Shape.Color.Blue, Shape.Pattern.DOTTED, 4);

I want do this without import Shape calss and its method in main 我想在不导入Shape calss及其主要方法的情况下执行此操作

The class is implemented as: 该类实现为:

public class Shape {
    Color color;
    Pattern pattern;

    public Shape(Color c, Pattern p) {
        this.color = c;
        this.pattern = p;
    }
    enum Color {
        BLUE, GREEN, RED
    }
    enum Pattern {
        DOTTED, STRIPED, ZIGZAG
    }
}


public class Square extends Shape {

    Integer length;
    Shape shape = new Shape(Color.BLUE,Pattern.DOTTED);

    public Square(Color c, Pattern p, int length) {
        super(c, p);
        this.length = length; // autoboxing
    }
}

Take a look at your imports, you have there something like this: 看一下您的导入,您将看到以下内容:

...
import <package_name>.Shape;
...

Just change it to: 只需将其更改为:

...
import <package_name>.Shape.Color;
...

Even if both Shape and Square are in the same package thus you don't have the import for Shape at all, adding this import will do the job. 即使ShapeSquare都在同一程序包中,因此您根本没有Shape的导入,添加此导入即可完成。

You have to declare explicitly the imports for nested classes. 您必须显式声明嵌套类的导入。 Perhaps your IDE does not autocomplete the imports of nested classes by default. 默认情况下,也许您的IDE不会自动完成嵌套类的导入。

I just need to define the enum outside the shape class 我只需要在shape类之外定义枚举

public class Shape {
    Color color;
    Pattern pattern;

    public Shape(Color c, Pattern p) {
        this.color = c;
        this.pattern = p;
    }
enum Color {
     BLUE, GREEN, RED
}
 enum Pattern {
     DOTTED, STRIPED, ZIGZAG
}

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

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