面向对象之函数重载

class Person
{
    int id,age;

    Person()
    {
        id = 0;
        age = 10;
    }

    Person(int _id)
    {
        id = _id;
        age = 20;
    }

    /*Person(int _age)
    {
        id = 1;
        age = _age;
    }*/
    /*
    Test.java:15: 错误: 已在类 Person中定义了构造器 Person(int)
        Person(int _age)
        ^
1 个错误
    */
    Person(int _id,int _age)
    {
        id = _id;
        age = _age;
    }

    void setAge(int _age)
    {
        age = _age;
    }

    void display()
    {
        System.out.println("id="+id+",age="+age);
    }

    void display(String str)
    {
        System.out.println(str+"的id是"+id+",age是"+age);
    }
}
public class Test
{
    public static void main(String[] args)
    {
        Person p1 = new Person();
        p1.display();

        Person p2 = new Person(1);
        p2.display();

        Person p3 = new Person(22);
        p3.display();

        Person p4 = new Person(11,23);
        p4.display("Prince");
        
        System.out.println(max(10,20));
    }
    public static int max(int a,int b)
    {
        return a>b?a:b;
    }
    public static byte max(byte a,byte b)
    {
        return a>b?a:b;
    }
}
/*
总结:
1.函数重载分类
1)基本函数
2)构造函数
2.判断能否重载的简单标志
看调用函数时是否会产生歧义即可
3.函数重载的判定
函数名相同
参数不同(参数个数不同,参数类型不同)
4.public static int max(int a,int b)
    {
        return a>b?a:b;
    }
    public static byte max(byte a,byte b)
    {
        return a>b?a:b;
    }
    
在C++这样就会出错,而在java中,整数默认是int,小数默认默认是double
上面两个函数,就是参数的类型不同,因此可以构成重载


*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值