简体   繁体   中英

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

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.

You have to declare explicitly the imports for nested classes. Perhaps your IDE does not autocomplete the imports of nested classes by default.

I just need to define the enum outside the shape class

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
}

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