初始化
构造器确保初始化
构造函数/构造方法/构造器:不带返回值 和类同名
public class SimpleCOnstructor{
public static void main(String[] args){
for(int i=0;i<10;i++){
new Rock();
new Rock2((int)(Math.random()*10));
}
}
}
class Rock{
Rock(){
System.out.println("ROCK!!");
}
}
class Rock2{
Rock2(int i){
System.out.println("ROCK"+i+"!");
}
}
方法重载
区分重载方法
相同的名字,但是形参结构不同
public class Overloading{
public static void main(String[] args){
for(int i=0;i<5;i++){
tree t=new tree(i);
t.info();
t.info("overloading");
}
}
}
class tree{
int height;
tree(){
System.out.println("planting a seedling");
height=0;
}
tree(int h){
height=h;
}
void info(){
System.out.println(height);
}
void info(String s){
System.out.println(s+" "+height);
}
}
能否以返回值区分重载方法?
不行!!
调用的时候不指定返回值, 所以不行
默认构造器
只要添加了构造方法, 默认方法就没有了
除非自己填上
class Bird{
Bird(){}
Bird(int i){}
Bird(float f){}
}
this 关键字
对当前对象的引用
public class Banana{
int i;
void peel(int i){
System.out.println(i);
this.i=i;//this.i表示成员变量,i是参数 ->this是明确范围的
}
public static void main(String[] args){
Banana a=new Banana();
Banana b=new Banana();
a.peel(1);
b.peel(2);
}
}
public class Leaf{
int i=0;
Leaf increment(){
i++;
return this;
}
void print(){
System.out.print(i);
}
public static void main(String[] args){
Leaf l=new Leaf();
l.increment().increment().increment().print();//3
}
}
在构造器中调用构造器
public class Flower{
int petal=0;
tring s="inti value";
Flower(int p){
petal=p;
System.out.println(petal);
}
Flower(String ss){
s=ss;
System.out.println(s);
}
Flower(String s,int p){
this(p);//调用其他构造方法
this.s=s;
System.out.println(petal+s);
}
Flower(){
this("hello",47);
}
}