版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
1.方法的重载
- 同一个类中,方法名称相同,参数列表不同
- 编译器在编译时自动根据方法的签名来调用不同的方法
- 与返回值类型和返回值名称无关
方法的签名
- 方法的签名包括方法名和参数列表
- 一个类中,不可以有两个方法的签名完全相同,即一个类中不可以有两个方法的方法名和参数列表都完全一样
- 如果一个类知识方法名相同而参数列表不同,是可以的
public class Cashier{
public boolean pay(double money){...}
public boolean pay(double money){...}
}//编译错误
public class Cashier{
public boolean pay(double money){...}
public boolean pay(String cardDID,String cardPwd){...}
}//编译正确
方法重载
public class PayMoney{//A方式
public boolean payByCash(double money){...}
public boolean payByCard(String cardld,String cardPwd){...}
public boolean payByCheck(String compayname,double money){...}
}
public class PayMoney{//B方式
public boolean pay(double money){...}
public boolean pay(String cardld,String cardPwd){...}
public boolean pay(String compayname,double money){...}
}
编译时根据签名绑定调用方法
- 编译器在编译时会根据签名来绑定调用不同的方法,我们可以把重载的方法看成是完全不同的方法,只不过恰好方法名相同而已
public boolean pay(double money){...}//1
public boolean pay(String cardld,String cardPwd){...}//2
public boolean pay(String compayname,double money){...}//3
pay(111.11);//调用方法1
pay("123456","456789");//调用方法2
pay("baidu",666.66);//调用方法3
构造方法
- 常常用于给成员变量赋初值
- 与类同名,无返回值类型
- 在创建(new)时被自动调用
- 若自己不写构造方法,则编译器默认提供无参构造方法,若写了,则不再默认提供
- 构造方法可以重载
class Cell{
int row;
int col;
Cell(){
row=0;
col=0;
}
Cell(int row1,int col1){
row=row1;
col=col1;
}
}
Cell c=new Cell();
Cell cc=new Cell(1,2);
3.this关键字
- this:指代当前对象,哪个对象调的就是指哪个对象,方法中访问变量之前,默认都有个this
Cell c=new Cell()
c.row=2;
class Cell{
int row;
void drop(){
this.row++;//c.row++;----------c.row=3
}
}
this的用法
- this. 成员变量名------访问成员变量
class Cell{
int row;//成员变量
int col;
Cell(int row,int col){//局部变量
this.row=row;//就近原则
thhs.col=col;
}
void drop(){
this.row++;
}
}
- this.方法名()----调用方法
- this()--------------调用构造方法
public class Cell {
int row;//行号
int col;//列号
Cell(){
this(0);
}
Cell(int n){
this(n, n);
}
Cell(int row,int col){
this.row=row;
this.col=col;
}
4.引用类型数组
基本类型数组
数组是对象
- 在Java中,数组属于引用数据类型;
- 数组对象在堆中存储,数组变量属于引用类型,存储数组对象的地址信息,指向数组对象
- 数组的元素可以看成数组对象的成员变量(只不过类型全都相同)
引用类型数组的声明
- 数组的元素可以是任何类型,当然也包括引用类型
- eg:
Cell[] cells = new Cell[4];
- 注意:new Cell[4]实际是分配了4个空间用于存放4个Cell类型的引用,并不是分配了4个Cell类型的对象
//声明int型数组arr,包含3个元素
//每个元素都是int型
int[] arr=new int[3];
arr[0]=5;
int a=5;
//声明Cell型数组cells,包含4个元素
//每个元素都是Cell型,默认值为null
Cell[] cells=new Cell[4];
//cells[0]------------Cell类型
cells[0]=new Cell(2,5);
Cell c=new Cell(2,5);
引用类型数组的初始化
Cell [] cells=new Cell[4];//创建Cell数组对象
cells[0]=new Cell(2,5);//创建Cell对象
cells[1]=new Cell(3,6);
cells[2]=new Cell(4,7);
cells[3]=new Cell(5,8);
Cell[] cells=new Cell[]{
new Cell(2,5),
new Cell(3,6),
new Cell(4,7),
new Cell(5,8)
}
数组的类型是基本类型数组
- 数组的元素可以为任意类型,也包括数组类型
int [][] arr =new int[3][];
arr[0]=new int[2];
arr[1]=new int[3];
arr[2]=new int[2];
arr[1][1]=100;
- arr指向一个数组,该数组有三个元素,每个元素都是int类型数组,长度分别为2,3,2
- 这样的数组可以用来表示类似“矩阵”这样的数据结构。arr[i][j]可以认为访问行号为i,列号为j的那个元素。在其他的一些语言中有专门的表示这样结构的所谓二维数组;严格地讲,Java语言中没有真正的二维数组