标签:ges ++ 不同 boolean 个数 自动 and java rgs
1.方法重载
1)方法的签名
public class Test{
public void print(int x){...};
public void print(int x){...}; //编译错误,方法签名不能一样
}
public class Test{
public void print(int x){...};
public boolean print(int x){...}; //编译正确
}
2)方法的重载
在Java语言中,允许多个方法的名称相同,但参数列表不同,称之为方法的重载(overload)。
public class Sum {
public static void main(String[] args) {
int x = sum(5,6);
double y = sum(5.0,6.0);
System.out.println(x);
System.out.println(y);
}
public static int sum(int x,int y){
return x+y;
}
public static double sum(double x,double y){ //方法重载
return x+y;
}
}
/*
运行结果:
11
11.0
*/
3)构造方法
构造方法是在类中定义的方法,构造方法常用于实现对象成员变量的初始化,不同于其他的方法,构造方法定义有如下两点规则。
语法:
[访问修饰符] 类名(){
构造方法体;
}
3.1)this关键字的使用
this关键字用在方法体中,用于指向调用该方法的当前对象,简单来说:哪个对象调用方法,this指的就是哪个对象,只能用在方法中,方法中访问成员变量之前默认有个this. 。
public void drop(){
this.row ++; //将调用该方法对象的成员变量row+1,这样书写概念更佳清晰
}
//为了方便起见,在没有歧义的情况下可以省略this:
public void drop(){
row ++;
}
在构造方法中,用来初始化成员变量的参数一般和成员变量取相同的名字,这样会利于代码的可读性,但此时不能省略this关键字,是用来区分成员变量和参数。
public Cell(int row,int col){
this.row = row; //将参数列表中的row赋值给类中的成员变量cow
this.col = col;
}
3.2)默认的构造方法
class Sum{
int x,y;
Sum(int x,int y){
this.x = x;
this.y = y;
}
}
public class Test{
public static void main(String[] args){
Sum s = new Sum(); //编译错误,当定义了构造方法Sum(int x,inty){..}之后,编译器不再提供默认的构造方法了
}
}
3.3)构造方法的重载
为了使用方便,可以对一个类定义多个构造方法,这些构造方法都有相同的名称(类名),方法的参数不同,称之为构造方法的重载。一个构造方法可以通过this关键字调用另外的一个重载构造方法。
class Sum{
int x,y;
Sum(){
this.x = 0;
this.y = 0;
}
Sum(int x){
this.x = x;
this.y = x;
}
Sum(int x,int y){
this.x = x;
thix.y = y;
}
}
//以上构造方法重载可以通过this.调用构造方法来进行重载,如下所示
class Sum{
int x,y;
Sum(int x,int y){
this.x = x;
this.y = y;
}
Sum(int x){
this(x,x);
}
Sum(){
this(0,0);
}
}
2.引用类型数组
1)数组是对象

2)引用类型数组的声明

3)引用类型数组的初始化
//1.先声明再赋值
Emp[] e = new Emp[3];
e[0] = new Emp("Tom",26);
e[1] = new Emp("Jerry",28);
e[2] = new Emp("Andy",30);
//2.声明的同时赋值
Emp[] e = new Emp[]{
new Emp("Tom",26),
new Emp("Jerry",28),
new Emp("Adny",30)
};

4)数组的类型是基本类型数组
int[][] arr = new int[3][]; //arr指向一个数组,该数组有三个元素,每个元素都是int类型数组,长度分别是2,1,3。 arr[0] = new int[2]; arr[1] = new int[1]; arr[2] = new int[3]; arr[0][0] = 1; arr[0][1] = 2; arr[1][0] = 3; arr[2][0] = 4; arr[2][1] = 5; arr[2][2] = 6; arr[2][3] = 7;

标签:ges ++ 不同 boolean 个数 自动 and java rgs
原文地址:http://www.cnblogs.com/jmwm/p/6921032.html