static关键字(2)

什么时候变量声明为实例的,什么时候声明为静态的?

  如果这个类型的所胡对象的某个属性值都是一样的,不建议定义为实例变量,浪费内存空间。建议定义为类级别特征,定义为静态变量,在方法区中只保留一份,节省内存开销。

  一个对象一份的是实例变量。

  所有对象一份的是静态变量。

public class Person {
public static void main(String[] args) {
chinese p1=new chinese("张三","中国","416574313246");
chinese p2=new chinese("李四","中国","486765435468");
System.out.println(p1.name);
System.out.println(p1.country);
System.out.println(p1.IDcard);
System.out.println(p2.name);
System.out.println(p2.country);
System.out.println(p2.IDcard);
}
}

//创建一个类
class chinese{
String name;
String country;
String IDcard;
//构造方法
public chinese() {
}

public chinese(String s1, String s2, String s3) {
this.name = s1;
this.country = s2;
this.IDcard = s3;
}
}

 注:创建的类不要写在main方法中,构造方法用来初始化变量,并且给变量赋值。构造方法名要与类名相同:public 类名

 

 

=======================================================================================================================================================

public class Person {
public static void main(String[] args) {
//访问中国人的国籍
//静态变量应该使用类名.的方式访问
System.out.println(chinese.country);//中国
chinese p1=new chinese("张三","416574313246");
chinese p2=new chinese("李四","486765435468");
System.out.println(p1.name);
System.out.println(p1.IDcard);
System.out.println(p2.name);
System.out.println(p2.IDcard);
}
}

//创建一个类
class chinese{
String name;
static String country="中国";
String IDcard;
//构造方法
public chinese() {
}

public chinese(String s1, String s3) {
this.name = s1;
this.IDcard = s3;
}
}

 =================================================================================================

public class Person {
public static void main(String[] args) {
//静态变量应该使用类名.的方式访问静态变量
System.out.println(chinese.country);//中国
chinese p1=new chinese("张三","416574313246");
chinese p2=new chinese("李四","486765435468");
System.out.println(p1.name);
//实例的:一定需要使用“引用.”来访问
//静态的:建议使用“类名.”来访问,但使用“引用.”也行(不建议使用“引用.”)。
System.out.println(p1.country);//中国
//p1是空引用
p1=null;
//分析这里会不会出现空指针异常?
//不会出现空指针异常。因为静态变量不需要对象的存在,实际上以下手代码在运行的时候,还是:
System.out.println(p1.country);

System.out.println(p1.IDcard);
}
}

//创建一个类
class chinese{
String name;
static String country="中国";//类加载的时候就被初始化
String IDcard;
//构造方法
public chinese() {
}

public chinese(String s1, String s3) {
this.name = s1;
this.IDcard = s3;
}
}

结论:
  空指针异常只有在什么情况下都会发生呢?
    只有在“空引用”访问“实例”相关的,都会出现空指针异常。

3.static关键字

  3.1 static修饰的统一都是静态的,都是类相关的,不需要new对象。直接采用“类名.”访问。

  3.2 当一个属性是类级别的属性,所有对象的这个属性的值是一样的,建议定义为静态变量。

  

posted @ 2022-05-06 15:56  开山y  阅读(19)  评论(1编辑  收藏  举报