Java 重载方法实现加法运算:不同数据类型加法示例
以下是使用 Java 语言编写的 Addition 类代码:
public class Addition {
public int add(int num1, int num2) {
return num1 + num2;
}
public long add(long num1, long num2) {
return num1 + num2;
}
public float add(float num1, float num2) {
return num1 + num2;
}
public double add(double num1, double num2) {
return num1 + num2;
}
public String add(String str1, String str2) {
return str1 + str2;
}
public ComplexNumber add(ComplexNumber num1, ComplexNumber num2) {
double real = num1.getReal() + num2.getReal();
double imaginary = num1.getImaginary() + num2.getImaginary();
return new ComplexNumber(real, imaginary);
}
public static void main(String[] args) {
Addition addition = new Addition();
int num1 = 5, num2 = 10;
long longNum1 = 100000000000L, longNum2 = 200000000000L;
float floatNum1 = 3.14f, floatNum2 = 1.23f;
double doubleNum1 = 3.141592653589793, doubleNum2 = 2.718281828459045;
String str1 = 'Hello, ', str2 = 'world!';
ComplexNumber complexNum1 = new ComplexNumber(2, 3);
ComplexNumber complexNum2 = new ComplexNumber(-1, 2);
System.out.println('int addition: ' + addition.add(num1, num2));
System.out.println('long addition: ' + addition.add(longNum1, longNum2));
System.out.println('float addition: ' + addition.add(floatNum1, floatNum2));
System.out.println('double addition: ' + addition.add(doubleNum1, doubleNum2));
System.out.println('string addition: ' + addition.add(str1, str2));
System.out.println('complex number addition: ' + addition.add(complexNum1, complexNum2));
}
}
class ComplexNumber {
private double real;
private double imaginary;
public ComplexNumber(double real, double imaginary) {
this.real = real;
this.imaginary = imaginary;
}
public double getReal() {
return real;
}
public double getImaginary() {
return imaginary;
}
public String toString() {
return real + ' + ' + imaginary + 'i';
}
}
在 Addition 类中,我们定义了 6 个重载的 add 方法,分别用于对整型、长整型、浮点型、双精度浮点型、字符串和复数进行加法运算。其中,复数的加法运算需要使用另一个类 ComplexNumber 来表示复数,并在 Addition 类中定义了一个 add 方法用于对两个复数进行加法运算。
在 main 方法中,我们创建了一个 Addition 类的实例,并分别调用了 6 个重载的 add 方法,测试了其效果。输出结果如下:
int addition: 15
long addition: 300000000000
float addition: 4.37
double addition: 5.859874482048838
string addition: Hello, world!
complex number addition: 1.0 + 5.0i
通过以上示例,您可以了解到如何在 Java 中使用重载方法实现不同数据类型的加法运算,并使用 ComplexNumber 类来表示复数。这将有助于您更好地理解 Java 的面向对象编程概念,并增强您的编程能力。
原文地址: https://www.cveoy.top/t/topic/j9X0 著作权归作者所有。请勿转载和采集!