首先我们要知道static能修饰那些东西,1,属性 2,方法 。
static修饰属性
话不多说我们直接上代码
class Car{
double price =10;
static String color="white";
public Car(double price) {//有参构造方法
this.price = price;
}
public Car() {//无参构造方法
this.price=900;
this.color="red";
}
@Override
public String toString() {
return price +"\t"+color;
}
public static void main(String[] args) {
Car car1=new Car();
Car car2=new Car(1000);
System.out.println(car1);
System.out.println(car2);
}
}
在上面这段程序中我们将color属性使用了static来修饰 在创建car1的对象过程中静态属性首先被加载在方法区 并且修改了color的值 然而我们在创建car2的时候并没有改变color的值,但car2的color输出的却不是white这说明color并没有被再次加载而是使用car1的color的值。这就说明被static修饰的属性只会加载一次并且被本类所有对象共享
static修饰方法
static修饰的方法只能访问静态成员,无需创建对象,可以直接使用类名去访问类的方法
今天我们先聊到这里,日后慢慢更新
--------------------------------------------------------------------------------------------------------------------------------
我来更新了
问题一
static方法中可以用this和super吗?
答:this主要作用是代指对象,我们首先知道的是static方法会先于对象创建前加载,如果在加载static的过程出现了this编译器无法识别this因为此时还没创建对象,就像爸爸还没出生而儿子就已经存在这时非常不合理的。同理我们可知super关键字我们主要是在在继承中调用父类成员用的,如果将super使用在static方法中在加载时会因为没用父类而报错,因为static类加载早于父类。
问题二
this可以调用satic方法吗?
虽然static方法中不可以用使用this,但this可以调用static方法,下面我们看段代码
class Test1{
public static void main(String[] args) {
Father father = new Father();
father.print();
}
}
class Father{
static void work(){
System.out.println("父亲可以工作");
}
void print(){
this.work();//这里我们使用this访问了static方法
}
}