代码
package com.java.test;

public class T {
//类变量,静态变量
public static String s="srx";
public String s1="zf";
public static void main(String args[]){
System.out.println(
"s=="+s);
System.out.println(
"T.s=="+T.s);


//通过类可以调用,通过实例更可以调。newy一个东西,会占用内存空间
T t= new T();
T t1
= new T();
t1.s
="heihei";
//验证一个类中的不同实例的static变量共享一个内存空间,下面这个t1.s给s赋值,把static类型String s已经改变了,所以下面所有的打印出来的都是改变后的s值。
System.out.println("t.s=="+t.s+",t1.s=="+t1.s+",T.s=="+T.s);

a();
T.a();
t.b();
}

public static void a(){
System.out.println(
"a()方法");
}
public void b(){
System.out.println(
"b()T.s=="+T.s);;
}
}

输出结果如下:

  /*打印结果
* s==srx
T.s==srx
t.s==heihei,t1.s==heihei,T.s==heihei
a()方法
a()方法
*/

第二个:
package com.java.test;

public class T1 {

//类变量,静态变量
public static String s="srx";
public String s1="zf";
public static void main(String args[]){
//一个类的静态方法能够直接(不用new实例)调用静态变量。
System.out.println("s=="+s);
/*一个类的静态方法不能够直接访问非静太变量,只能new一个类之后,用实例调用非静态属性
* Cannot make a static reference to the non-static field s1
System.out.println("非静态s1=="+s1);
*/
/*Cannot make a static reference to the non-static field T1.s1
System.out.println("T1.s1=="+T1.s1);
*/

System.out.println(
"T.s=="+T1.s);

//通过类可以调用,通过实例更可以调。newy一个东西,会占用内存空间
T1 t= new T1();

System.out.println(
"t.s1=="+t.s1);

T1 t1
= new T1();
t1.s
="heihei";
//验证一个类中的不同实例的static变量共享一个内存空间,下面这个t1.s给s赋值,把static类型String s已经改变了,所以下面所有的打印出来的都是改变后的s值。
System.out.println("t.s=="+t.s+",t1.s=="+t1.s+",T1.s=="+T1.s);
/*这里不能用this
//this.
*/
t.b();

}

public static void a(){
System.out.println(
"a()方法");

}
public void b(){
/*//在这里可以用this.
this.
*/
System.out.println(
"b()T1.s=="+s);
a();
T1 t3
= new T1();
t3.a();
c();
t3.c();
System.out.println(
"b()T1.s1=="+s1);
System.out.println(
"b()T1.t3.s1=="+t3.s1);
}
public void c(){
System.out.println(
"c()");

}

}

相关文章:

  • 2021-12-06
  • 2021-10-07
  • 2022-12-23
  • 2021-09-05
  • 2021-12-18
  • 2021-08-03
  • 2021-09-18
猜你喜欢
  • 2021-07-19
  • 2022-01-01
  • 2022-02-17
  • 2022-01-22
  • 2022-01-11
  • 2021-07-28
相关资源
相似解决方案