简体   繁体   中英

Is there any way to use methods from interface and class specified when creating object from interface referance?

We got this scenario:

public class Shape{
    private String type;
   
}

public interface ShapeI{
    String calculateField();
}

public class Circle extends Shape implements ShapeI{

    private double radius;  
  
    @Override
    public String calculateField() {
        return "PiRadisSQ";
    }

    public void circleMethod() {
        System.out.println("circleMethod");
    }   
}

public class Main  {
    public static void main(String[] args) {
        ShapeI circle = new Circle();
        circle.calculateField(); // can use it
        circle.circleMethod(); // can't use it
    }
}

circleMethod() is logically spécifique to Circles and does not apply to all Shapes. The interface methods must be implemented by all Classes which implement it. The interface can therefore include methods which are applicable to all Shapes,area, perimeter etc, but will be implemented in different ways according to the shape in question.

"

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