static修饰实例

public class ExtB{
/*类变量和实例变量都是全局变量,无须初始化
* 两者的区别是:
* 类变量由static修饰,由所有对象共享
* 实例变量不用static修饰,由每个对象各自占有自己的,类似于在实例化时创建了实例变量的副本
* */
static int i = 10;//不必须初始化
int j = 20 ;//不必须初始化
public ExtB(int j) {
this.j = j;
}
public ExtB() {
}
public void hello(){
System.out.println(“Hello,我是非静态方法~”);
System.out.println(“Hello,我是非静态方法~我在调用类变量i= ” + i);
System.out.println(“Hello,我是非静态方法~我在调用实例变量j= ” + j);
System.out.println(“Hello,我是非静态方法~我在调用静态方法helloStatic()”);
helloStatic();
}
public void hello1(){
hello();//非静态方法调用非静态方法没有问题
System.out.println(j);//非静态方法调用非静态变量没有问题
}
public static void helloStatic() {
System.out.println(“Hello,我是静态方法~”);
System.out.println(“Hello,我是静态方法~我在调用类变量i= ” + i);
//System.out.println(“Hello,我是静态方法~我在调用实例变量j= ” + j);//报错,非静态变量不能直接调用
}
public static void main(String[] args) {
int x;//局部变量必须初始化

    ExtB extb1 = new ExtB(30);
    ExtB extb2 = new ExtB(40);
    System.out.println("ExtB.i= "+ExtB.i);
    System.out.println("extb1.i= "+extb1.i);
    System.out.println("extb2.i= "+extb2.i);
    System.out.println("--------------------");

    //System.out.println("ExtB.j= "+ExtB.j);//报错,非静态变量不能直接调用
    System.out.println("new ExtB(1).j= "+new ExtB(1).j);//在静态方法中不能访问类的非静态成员变量和非静态成员方法,因为非静态成员方法/变量都是必须依赖具体的对象才能够被调用。  
    System.out.println("extb1.j= "+extb1.j);
    System.out.println("extb2.j= "+extb2.j);
    System.out.println("--------------------");

    //System.out.println(x);//报错,局部变量必须初始化

    ExtB.helloStatic();//调用静态方法,没有问题,或者直接helloStatic();也行
    System.out.println("--------------------");

    //hello();//报错,非静态方法不能直接调用
    new ExtB().hello();
    System.out.println("--------------------");

}

}

猜你喜欢

转载自blog.csdn.net/qq_21967531/article/details/81537289