面向对象之函数重载
2016-07-03 17:52
197 查看
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
上面两个函数,就是参数的类型不同,因此可以构成重载
*/
{
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
上面两个函数,就是参数的类型不同,因此可以构成重载
*/
相关文章推荐
- 今天学习利用Service下载图片,记录一点小东西!
- 计蒜客 百度地图的实时路况
- excel文件的下载
- BUG-getContainingNode(): node module not found
- 个人博客
- markdown笔记
- Hive HBase Integration 集成
- 数据结构学习笔记(一) 顺序表
- boost::shared_ptr boost::make_shared
- php用curl调用接口方法,get和post两种方式
- 证书相关概念及使用openssl生成自认证证书
- 深入理解JavaScript的Promise
- 排序算法(2)——归并排序
- 2016年6月前端工作笔记
- css 浮动
- (总结)play framework框架
- 【cqbzoj】1785:残缺棋盘上放车的方案数 --状压dp --输入毁一生
- [javaEE] EL表达式调用java方法
- ps钢笔工具/路径/钢笔抠图/字体工具
- 【cqbzoj】:1330 Prime DP(Ahio2001 质数和分解)