官术网_书友最值得收藏!

  • The Java Workshop
  • David Cuartielles Andreas G?ransson Eric Foster Johnson
  • 565字
  • 2021-06-11 13:05:22

Overloading Methods and Constructors

One very interesting property of Java is how it allows you to define methods that have the same conceptual functionality as each other by using the same name but changing either the type or number of parameters. Let's see how this could work.

class Age {

    public double a = 0;

    public void setAge ( double _a ) {

        a = _a;

    }

    public void setAge ( int year, int month ) {

        a = year + (double) month / 12;

    }

    public double getAge () {

        return a;

    }

}

class Example09 {

    public static void main(String[] args) {

        Age age = new Age();

        age.setAge(12.5);

        System.out.println(age.getAge());

        age.setAge(9, 3);

        System.out.println(age.getAge());

    }

}

Note

Look at the highlighted portion in the preceding code. As we are taking the integer parameter month and dividing it by a number, the result of the operation will be a double. To avoid possible errors, you need to convert the integer into a floating comma number. This process, called casting, is done by adding the new type between brackets in front of the object, variable, or operation we want to convert.

The result of this example is:

12.5

9.25

Process finished with exit code 0

This shows that both methods modify the a variable in the Age class by taking different sets of parameters. This same mechanism for having conceptually equivalent results from different blocks of code can be used for the constructors of a class, as shown in the following example.

class Age {

    public double a = 0;

    Age ( double _a ) {

        a = _a;

    }

    Age ( int year, int month ) {

        a = year + (double) month / 12;

    }

    public double getAge () {

        return a;

    }

}

class Example10 {

    public static void main(String[] args) {

        Age age1 = new Age(12.5);

        Age age2 = new Age(9, 3);

        System.out.println(age1.getAge());

        System.out.println(age2.getAge());

    }

}

In this case, as a way to show the functionality, instead of instantiating a single object and calling the different methods to modify its variables, we had to create two different objects, age1 and age2, with one or two parameters, as those are the possible options offered by the constructors available in the Age class.

主站蜘蛛池模板: 大兴区| 宁夏| 通辽市| 金山区| 桐柏县| 金平| 昭苏县| 姜堰市| 柯坪县| 湖州市| 肇庆市| 平潭县| 丰城市| 吴忠市| 砚山县| 太保市| 冕宁县| 三亚市| 高雄市| 腾冲县| 华蓥市| 山东省| 汾西县| 睢宁县| 都兰县| 会东县| 阿拉善盟| 牡丹江市| 兴文县| 景东| 灵丘县| 凤阳县| 舞阳县| 嘉鱼县| 大埔县| 夏津县| 房产| 大兴区| 都匀市| 顺昌县| 新密市|