类的构造器名必须与类名一致,且无返回类型,通过参数类型的不同(即使顺序不同也行)可以重载构造器,也可以以此技巧重载方法
this关键字:表示对“调用方法的那个对象的引用”,也可将当前对象传递给其他方法,也可通过this在构造器中调用构造器
在方法内部调用同一类的另一方法无需使用this
static方法中不得调用this,仅通过类本身便能调用static方法,产生类似于全局方法的效果
例如:class Leaf{
int i=0;
Leaf increment(){
i++;
return this;}
例如:class Peeler{
static Apple peel(Apple apple){
/*.......*/
return apple;} }
class Apple{
Apple getpeeled(){
return Peeler.peel(this);} }
在构造器中调用构造器(注意:不能在除构造器之外的任何方法中调用构造器)
例如:class Flower{
String s="Hello";
Flower(String s){
/*.......*/ }
Flower(int petal){
/*.......*/}
Flower(String s,int petal){
this(petal);//调用Flower(int petal)
this.s=s;//给构造器参数s赋值“Hello”} }
清理:(手动机制)垃圾回收仅回收垃圾占据的内存
1.对象可能不被垃圾回收
2.垃圾回收并不等于“析构”
3.垃圾回收只与内存有关
通常调用finalize()与java使用本地方法引入c&c++代码有关
finalize()不能作为所谓的java中的"析构"函数,其应用可以是终结条件的验证
强制执行终结动作:System.gc();
成员初始化:
方法的局部变量未经初始化会报错;
类的数据成员未经初始化会给予其默认值,未经初始化的对象引用为null。
类的数据成员在定义处即可进行初始化,类成员的定义顺序决定初始化顺序,静态对象优先于非静态对象进行初始化。
显式的静态初始化:
static int i;
static Cup cup1;
static{
i=19;
cup1=new Cup(1);
/*........*/}
显式的非静态初始化:(少了static关键字)
int i;
Cup cup1;
{
i=19;
cup1=new Cup(1);
/*........*/}
在java中允许将一个数组赋给另一个数组,数组元素个数可由arr.length提供
使用System.out.print(Arrays.toString(arr))可以打印一维数组arr
可变参数列表:(协助重载方法)
所有类都直接或间接的继承自Object类,故可通过创建以Object数组为参数的方法建立可变参数:
定义: static void printArray(Object[ ] args){(类型,长度不受限制)
for(Object obj:args){
/*..........*/}
/*.................*/}
调用:printArray(new Integer(19),new Float(1.9),new Double(11.11));
printArray("one","two","three");
printArray(new A(),new B(),new C());//也就是说方法中的参数类型不受限制
也可:定义:static void f(int id1,String...str1){(类型限制,长度不限)
for(String s:str1){
/*...............*/}
/*......................*/}
调用如:f( );不可行,必须带有参数
枚举:(enum也看作是一个类)
例如:定义:public enum Spiciness{
NOT,MILD,MEDIUM,HOT,FLAMING}
调用:Spiciness spn=Spiciness.HOT;
System.out.print(spn);(编译器自动调用.toString()以便打印)
for(Spiciness s:Spiciness.values()){//.values()获取枚举值
System.out.print(s+",ordinal "+s.ordinal()); //.ordina()获取顺序
enum协助switch:
完整实例:
1 enum Spiciness{ 2 NOT,MILD,MEDIUM,HOT,FLAMING 3 } 4 class Burrito{ 5 Spiciness degree; 6 public Burrito(Spiciness degree){ 7 this.degree=degree; 8 } 9 public void describe(){ 10 switch(degree){ 11 case NOT:/*..........*/break; 12 case MILD:/*..........*/break; 13 /*...........*/ 14 } 15 } 16 }