方法递归
递归分类:直接递归:方法在代码内部调用当前方法本身。
A->A->A->....
间接递归:A方法调用B方法,B方法调用当前方法,多个方法之间互相调用。
- >B->A->B...
递归条件没有设置会出现死递归即栈溢出。
int count(int n) {
if (n == 1) {
return 1;
} else {
return n + count(n - 1);
}
}
对象数组
说明:数组可以是引用数据类型,也可以是自己创建的引用数据类型,例如:
Student[] arr= new Student[5];
封装
面向对象三大特性:封装、继承、多态。
封装指对属性或方法进行权限的封装。
当前类 当前包 当前项目 其他包子类 其他包非子类
Private √
缺省 √ √
Protected √ √ √ √
Public √ √ √ √ √
权限符越小访问的地方越少。
权限符可以修饰:类(public 和缺省)除非是内部内才可以使用其他的权限符。 属性一般使用private设置为私有,通过get、set方法来设置属性和获取 属性值。
方法private只能在当前类中调用方法。
构造器
Student stu = new Student();
引用对象实例时后面跟的括号指的就是构造器,不填参数指空参构造器,所有类都有一个空参的构造器,当生成其他构造器(包括空参),系统默认的空参构造器就没了,通过在实例对象时的括号参数不同调用不同的构造器。
public Employee(int id, String name, double salary, char sex) {
this.id = id;
this.name = name;
this.salary = salary;
this.sex = sex;
}
JavaBean
当类中包含私有属性、公用get方法、公用set方法、空参构造器。
this关键字
指当前对象。
在方法中形参和属性名称一样使用this关键字表示当前对象的属性。
在构造器中使用this()表示空参构造器。
public class test {
public static void main(String[] args) {
int id = 10;
method method = new method();
method.test(10);
}
}
class method {
int id = 15;
public method() {
}
public void test(int id) {
System.out.println(id);//10
System.out.println(this.id);//15
}
}