1. 程序控制
1.1 if-else和switch细节
- switch不能解决范围类型的条件
- switch, 条件满足,可以执行多个代码段(无break时)。
- &&和||都是从左到右执行。不能左右交换。【a&&b不等于b&&a】
1.2 三元运算符
String des;
if(rank == "H1"){
des = "very good";
} else{
des = "good";
}
String des = (rank == "H1") ? "very good":"good";
1.3 数据类型细节
- ==: 只能对比基础数据类型。对比的是地址是否相同。
- 对于非基础数据类型使用equals来进行比较。
2. 循环loop
2.1 使用while/ for的情况?
- 知道具体要循环几次,用for。
- 达到某个condition就结束循环,用while。
2.2 break、continue、exit()
- break: 结束当前整个循环。
- continue:结束当前小循环,继续执行下一次小循环。
- System.exit():立刻结束整个程序。
3. class
- class有一个不同,两个相同。【属性是相同的,】
- public当前的功能能在别的class种使用。
private只在当前的class中使用。 - void:表示不需要method有return。
- class内部的结构是无序的。
- class的属性instance variable全部放在最前面。
3.1 instance variable属性
- 当instance variable设置为public,则外部可以肆无忌党的改变。
- 获得该object的属性,get method【自动生成:】
- 修改该object的属性,set method【自动生成:】
- 如果当前的class只有get没有set的时候,证明该class不可修改,成为immutable class。【string是一个immutable class。】
public class People(){
private name;
private age;
public String getName(){
return name;
}
public int getAge(){
return age;
}
public void setName(String name){
this.name = name;
}
public void setAge(int age){
this.age = age;
}
}
3.2 构造函数constructor function
- 名字 和class完全相同
- 没有return type。
- new: 表示的就是调用一个构造函数。
- 可以有好几个构造函数!
public class People{
private name;
private age;
public People(String name, int age){
this.name = "Leo";
this.age = age;
public People(String name){
this.name = "Leo";
}
public People(int age){
this.age = age;
}
public class main{
People leo = new People("Leo", 25);
People Skylar = new People("Skylar", 23);
People Lydia = new People("Lydia");
People unknown = new People(24);
}
3.3 this和return
- return的使用。
int c = add(1, 2);
public static int add(int a, int b){
return a + b;
}
- this: 用来解决冲突的,代表this表述的量一定是instance variable。
【this.name】 表示的是instance variable的name。
【name】表示的是方法输入的name,就近匹配。
3.4 variable
- local variable: 在函数当中的,无初始值。
- instance variable: 在class中,不属于任何一个method,会被初始化。
- constant variable:在class中,不属于任何一个method,不可再修改。
【加上final】 - static variable:在class中,有static修饰的变量,会被初始化。它是整个class的object共享的指标。ex.整个class的人数。
private final int year = 2024;