java notes 05-1

初始化

构造器确保初始化

构造函数/构造方法/构造器:不带返回值 和类同名

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);
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值