Java:添加两个对象 [英] Java: add two objects

查看:136
本文介绍了Java:添加两个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 Greenfoot 制作一个项目,我做了一个假想的数字课程。在我的项目中,我发现需要将两个虚构对象一起添加(或减去或其他),是否有办法添加两个这样的对象?所以这就是它在完美世界中的表现:

I was making a project in Greenfoot and I made an imaginary number class. In my project I found a need to add (or subtract, or whatever) two imaginary objects together, is there a way to add two objects like that? So this is how it would look in a perfect world:

    Imaginary i1 = new Imaginary(1.7,3.14);
    Imaginary i2 = new Imaginary(5.3,9.1);
    //the class Imaginary has parameters (double real, double imaginary)
    Imaginary i3 = i1+i2;

这可能吗?

推荐答案

Java 没有运算符重载

例如, BigDecimal a + b 而不是 a.add(b),$ c>会更受欢迎。

For example, BigDecimal would be a lot more popular if you could write a + b instead of a.add(b).

方式1

Imaginary i3 = i1.add(i2);

方法:

public static Imaginary add(Imaginary i2)
{
    return new Imaginary(real + i2.real, imaginary + i2.imaginary);
}

方式2

Imaginary i3 = add(i1, i2)

方法:

public static Imaginary add(Imaginary i1, Imaginary i2)
{
    return new Imaginary(i1.real + i2.real, i1.imaginary + i2.imaginary);
}

运算符重载肯定会使设计比没有它更复杂,它可能会导致更复杂的编译器或减慢JVM。

Operator overloading would have definitely made design more complex than without it, and it might have led to more complex compiler or slows the JVM.

这篇关于Java:添加两个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆