初始化
構造器確保初始化
構造函數/構造方法/構造器:不帶返回值 和類同名
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);
}
}