使用方法重载计算圆形的面积的Java程序
我们可以使用Java中的方法重载来计算圆形的面积。“方法重载”是Java中的一项特性,它允许在同一个类中编写多个具有相同名称的方法。它使我们能够声明多个具有相同名称但签名不同的方法,即方法的参数数量可能不同,或者参数的数据类型可能不同。
现在,让我们以“圆形的面积”为例,在Java中实现方法重载。在进入示例之前,让我们了解本文中使用的术语。
圆形的面积
圆形的面积是指圆形在二维平面中所覆盖的区域。
Area of Circle : πr^2 where π : A Greek mathematical symbol = 3.14 or 22/7. r : radius of circle.
在下面的示例中,我们将使用圆形的面积作为示例,通过更改参数的数据类型来在Java中实现方法重载。
使用方法重载计算圆形面积的步骤
以下是使用方法重载计算圆形面积的步骤:
步骤1 − 编写一个自定义类来计算圆形的面积。
步骤2 − 在公共类的main方法中初始化两个不同数据类型的变量。
步骤3 − 在公共类的main方法中创建一个自定义类的对象。
步骤4 − 使用创建的自定义对象调用特定方法来计算圆形的面积。
方法
以下是计算圆形面积的方法:
基于半径类型的使用方法重载计算圆形面积的Java程序
在这个例子中,我们使用基本的公式计算圆形的面积,并在Java中实现了方法重载。
示例
//Java Code to achieve Method Overloading in Java by Area of Circle
import java.io.*;
class Area {
// In this example area method is overloaded by changing the type of parameters.
double PI = Math.PI;
//Math.PI is a constant value in Java in the Math library.
public void areaOfCircle(double radius) {
double area = 0;
area = PI * radius * radius;
System.out.println("Area of the circle is :" + area);
}
public void areaOfCircle(float radius ) {
double area= 0;
area = PI * radius * radius;
System.out.println("Area of the circle is :" + area);
}
}
public class Main {
public static void main(String args[]) {
Area Object = new Area();
float radius_1 = 7;
Object.areaOfCircle(radius_1);
double radius_2 = 3.5;
Object.areaOfCircle(radius_2);
}
}
输出
Area of the circle is :153.93804002589985 Area of the circle is :38.48451000647496
时间复杂度:O(1)
辅助空间:O(1)
使用直径和方法重载计算圆形面积的Java程序
我们可以使用另一种公式计算圆形的面积,其中我们使用直径并在Java中实现方法重载。
示例
//Java Code to achieve Method Overloading in Java by Area of Circle by alternative formula.
import java.io.*;
import java.util.*;
class Area {
// In this example area method is overloaded by changing the type of parameters.
double PI = Math.PI;
//Math.PI is a constant value in Java in Math library.
public void areaOfCircle(double diameter) {
double area = 0;
area = PI * (diameter/2)*(diameter/2);
System.out.println("Area of the circle is :" + area);
}
public void areaOfCircle(float diameter) {
double area= 0;
area = PI * (diameter/2)*(diameter/2);
System.out.println("Area of the circle is :" + area);
}
}
public class Main {
public static void main(String args[]) {
Area Object = new Area();
double diameter_1 = 14;
float diameter_2 = 7;
Object.areaOfCircle(diameter_1);
Object.areaOfCircle(diameter_2);
}
}
输出
Area of the circle is :153.93804002589985 Area of the circle is :38.48451000647496
时间复杂度:O(1)
辅助空间:O(1)
因此,在本文中,我们学习了如何通过使用计算圆形面积的示例,通过更改参数的数据类型来在Java中实现方法重载。
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP