一、This关键字
1、this在普通方法可以放在任意位置,在构造方法必须是第一条语句,this不能用于static(静态)方法
2、静态方法不能在静态方法中调用,但是可以间接调用非静态方法,静态方法中不能出现this调用
public class TestThis {
int a,b,c;
TestThis(){
System.out.println("new");
}
TestThis(int a,int b){
//Hello(); // //这样是无法调用构造方法的!
this(); //调用无参的构造方法,并且必须位于第一行
a = a;//这里都是指的局部变量而不是成员变量
this.a = a;//这样就区分了成员变量和局部变量. 这种情况占了this使用情况的大多数
this.b = b;
}
TestThis(int a,int b,int c){
this(a,b);
this.c = c;
//调用无参的构造方法,并且必须位于第一行
}
void sing(){}
void chifan(){
this.sing(); //sing();
System.out.println("hello");
}
public static void main(String[] args){
TestThis hi = new TestThis(2,3);
hi.chifan();
}
}
二、static静态方法
一般工具类中的方法定义为static,static变量存储在方法区
public class TestStatic {
int a;
static int width;
static void gg(){
System.out.println("gg");
}
void tt(){
System.out.println("tt");
}
public static void main(String[] args){
TestStatic hi = new TestStatic();
TestStatic.width = 2;
TestStatic.gg(); //gg();
hi.gg();
gg();
}
}
三、packge
每个地方需要不同的包,包内不能有重名文件命名以点为界限逐级确定
四、封装
封装:我们程序设计要追求“高内聚,低耦合”
高内聚:就是类的内部数据操作细节自己完成,不允许外部干涉;
低耦合:仅暴露少量的方法给外部使用
(set和get一组进行封装)