编程知识 cdmana.com

Programming of interface in Java

What I want to achieve : To design a Shape Interface and its two implementation classes Square and Circle. Requirements are as follows :

Shape There is an abstract method in the interface area(), The receive method has a double Parameters of type , Return to one double Result of type .

Square and Circle Implemented in the Shape Interface area() Abstract method , Find the area of a square and a circle respectively and return .

Create... In the test class Square and Cirecle object , And calculate the side length as 2 The area and radius of the square are 3 Circular area of .




Take the answer :

Give me an example , You don't have to write the constructor :

interface Shape{    public double area(double n);}class Square implements Shape{    double edge;    public Square(double edge){        this.edge = edge;    }    @Override    public double area(double n) {        return n*n;    }}class Circle implements Shape{    double radius;    public Circle(double radius){        this.radius = radius;    }    @Override    public double area(double n) {        return Math.PI*n*n;    }}public class TestShape{    public static void main(String[] args) {        Square s = new Square(2);        Circle c = new Circle(3);        System.out.println(" Square area :"+s.area(2));        System.out.println(" Circular area :"+c.area(3));    }}

版权声明
本文为[CSDN Q & A]所创,转载请带上原文链接,感谢
https://cdmana.com/2022/134/202205072041111671.html

Scroll to Top