static关键字
定义: static是静态的, 是一个成员修饰符, 只能修饰成员,不能修饰局部
public class Static{
public Static int age = 1; //正取,可以修饰成员变量
public static void main(String[] args) {
int static = 1 ;///错误,不能修饰局部变量
}
}
修饰变量: 静态变量 | 类变量
修饰方法: 静态方法 | 类方法
静态内容的使用方式:
1.对象使用
引用名.静态变量名
引用名.静态方法名()
2.通过类名使用
类名.静态变量名
类名.静态方法名()
注意
1.成员都是属于对象的,静态的内容是属于类的
2.静态的变量在静态区中存在,是独一份的,
3.静态变量是所有对象共享的资源,在类第一次加载之后就初始化
4.成员的变量在对象的内存空间中,跟随对象存在的,有一个对象就有一个成员
5.this不能再static修饰的方法中使用
6.静态的内容只能直接使用静态的内容,不能直接使用成员的内容,但是可以通过对象使用
7.成员内容可以直接使用静态的,也可以直接使用非静态的内容
举例:
public class Static{
public static void main(String[] args) {
Dog dog = new Dog();
dog.name = "旺财";
dog.age = 3;
dog.info();
//测试静态变量使用
System.out.println(dog.location);//方法名调用
System.out.println(Dog.location);//类名调用
//类名调用
Dog.wang();
//测试静态内容中是否可以直接使用成员和静态内容
test1();
StaticDemo01 s=new StaticDemo01();
s.test2();
}
//静态方法
static void test1(){
System.out.println("静态方法");
}
//成员内容
void test2(){
System.out.println("成员方法");
//测试成员的内容中可以直接使用静态的和非静态的内容
System.out.println(name);
System.out.println(this.id);
}
}
class Dog{
//成员变量
String name ;
int age ;
//静态地区, 所有人共享
static String location = "中国";
public Dog(){
}
public Dog(String name,int age ){
this.name= name;
this.age=age;
}
public static void wang(){
System.out.println("旺旺");
}
public void info(){
System.out.println(name+age);
}
}
this关键字
定义:
1.代指当前new的对象
2.构造器首行调用其他构造器
this 参数列表
注意: this必须在构造器首行使用,不能和其他构造器相互调用
作用:
1.区分同名变量问题:
this存储的是对象的地址
在成员方法中,this指代当前调用这个成员方法的对象
如果出现同名变量问题,使用this指代成员变量
如果不存在同名问题, this默认使用,可以省略
2.在构造器中,this指代当前new的对象
注意 : this 和 static 不能同时使用
public class ThisDemo01{
public static void main(String[] args) {
Cat c1 = new Cat();
c1.miao11();
Cat c2 = new Cat("小黑");
c2.miao11();
Cat c3 = new Cat("小黑","橘猫","黄色");
c3.miao11();
}
}
class Cat{
public string name;
public String type;
public String color;
public Cat(){
System.out.println("空构造");
}
//如果出现局部变量和成员变量同名问题,默认指代局部,就近原则
//this默认指代当前调用成员方法的对象
public Cat(string catName){
String name = "小白"; //新增局部变量
this.name = catName;
System.out.println("带参构造");
}
public Cat(string name,String cattype,String catcolor){
/*
name = catName;
type = cattype;
*/
this(catName,cattype);//调用本类中其他构造器,使用参数列表区分
color = catcolor;
System.out.println("带参构造");
}
public void miao(){
System.out.println("喵喵");
}
public void miao11(){
System.out.println(name+type+color);
}
}