浅谈java中万事万物皆对象:
java中,我们将功能和结构都封装到类中,通过类的实例化来实现具体的功能和结构。如:String、File、网络资源URL等。java在和前端HTML以及后端的数据库进行交互时,不管是前端还是后端在java层面上,其结构都体现为类和对象。
引用类型的对象只能存储两类值,null和地址值(包含数据类型)。
匿名对象: 我们在创建对象是没有给对象显式的赋上一个变量名。
匿名对象只能使用一次。
如下:
p.eat(new Food());
方法的重载:
在同一个类中允许存在一个以上的同名方法共存,只要它们的参数个数和参数类型不同即可。
总结: 两同一不同(同一个类、同一个方法名;不同的参数列表);与方法的权限修饰符、返回值类型、形参名和方法体都没有关系。
在通过对象调用重载的方法是通过方法名加形参列表的方式确定。
例如:
public class OverLoad{
public static void mian(String[] args){
}
public void getSum(int i,int j){
System.out.println(i+J);
}
public void getSum(double i,double j){
System.out.println(i+j);
}
public void getSum(String s ,int i){
System.out.println("3");
}
public void getSum(int i,String s){ // 注意参数顺序不同也算作是不同的参数列表
System.out.println("4");
}
}
方法形参的值传递机制:
形参:定义在方法参数列表中的参数;
实参:在调用方法时实际传递给形参的数据;
如果参数是基本数据类型,则实参传递给形参的是实参中真是存储的数据值。
如果参数是引用数据类型,则实参传递给形参的是实参中存储数据的地址值。
JDK5.0中新增的内容: (可变个数形参)
可变个数形参的格式:参数类型…变量名;
几个注意点:
可变个数形参的参数个数可变,可以是0、1、2、3。。。;
方法的重载中可变个数的形参不同也会构成重载;
方法的参数列表中只能有一个可变形参,且可变形参要放在参数列表的最后;
public class MethodArgsTest {
public static void main(String[] args) {
MethodArgsTest test = new MethodArgsTest();
test.show(12);
// test.show("hello");
// test.show("hello","world");
// test.show();
test.show(new String[]{"AA","BB","CC"});
}
public void show(int i){
}
public void show(String s){
System.out.println("show(String)");
}
public void show(String ... strs){
System.out.println("show(String ... strs)");
for(int i = 0;i < strs.length;i++){
System.out.println(strs[i]);
}
}
//不能与上一个方法同时存在
// public void show(String[] strs){
//
// }
//The variable argument type String of the method
//show must be the last parameter
// public void show(String ...strs,int i){
//
// }
}
递归方法的使用:
递归方法: 在一个方法体内调用它自身;
注意:递归含有一种隐式的循环,但是并没有循环语句;在使用递归时一定要向着已知的方向递归,否则就变成了无穷递归,类似于死循环。
public class RecursionTest{
public static void main(String[] args){
}
//递归方法
public int getSum(int m){
if(m == 1){
return 1;
}
else{
return m*getSum(m-1);
}
}
}