用构造器确保初始化
- 构造器的名称必须与类名完全相同。
- 类的构造器相当于一个创建对象时执行的方法,当不写构造器的时候,会默认为类提供一个无参构造器。
- 当写了一个有参数的构造器的时候,无参构造器便不会默认提供了,如果有需要的话,还是要再写。
class Rock {
//无参构造器
Rock(){}
//有参数构造方法
Rock(String str) {
//这相当于调用了上面的无参数构造器,构造器之间可以互相调用,不过要再构造器方法中的第一行代码中调用,并且要避免死循环。这里面也涉及到了方法重载,后面再说。
this();
System.out.println(str);
}
}
方法重载
所谓方法重载,也就是有多个方法,但是方法之间的名称相同,但是参数不一样,也是为了让同个方法表示不同的意义。
class Tree {
int height;
public void info() {
System.out.println("this tree's height is"+this.height);
}
public void info(int height) {
System.out.println("this tree's height is"+height);
}
}
区分重载方法
每个重载的方法都必须有一个独一无二的参数类型列表,要么是个数不一样,要么是同顺序的参数的类型不一样。不能用返回类型区分重载的方法。因为如果参数列表也一样的话,调用方法的时候, 编译器无法判断你调用的到底你哪个方法。
涉及基本类型的重载
基本类型能从一个较小的类型自动提升至一个较大的类型。
class PrimitiveOverloading {
void f(byte x) {
System.out.println("byte");
}
void f(int x) {
System.out.println("int");
}
void f(double x) {
System.out.println("double");
}
public void static main(String[] args) {
//结果:int;因为直接整形数默认为int,所以调用的是第二个方法,当没有第二个方法的时候,会向上提升,这时结果就会是double;
f(1);
//结果:byte;
f((byte)1);
}
}
this关键字
this的就是这个的意思,指的是当前对象。
public class Apple {
int weight;
public void setWeight(int weight) {
//这里指的当前对象的weight属性
this.weight=weight;
}
public void provide() {
//把当前对象的引用作为参数使用
Animal.eat(this);
}
}
static的含义
在static方法的内部不能调用非静态方法,反过来可以。因为static方法很像全局方法,static方法不算“面向对象”的。