G
N
I
D
A
O
L
W
e
l
c
o
m
e
: )

Java 变量

Java变量

1.变量的定义:
格式如下:
type identifier [ = value][, identifier [= value] ...] ;
示例:
//测试类
package com.run;

public class Demo01 {
private int A ;
public String names;
private String S1;
public String getS1(){
return S1;
}
public void setS1(String N){
S1 = N;
}
public int getA() {
return A;
}

public void setA(int a) {
A = a;
}
}
//测试方法

package com.run;

public class BL {
int A = 1000;
//定义一个变量并直接初始化赋值;
int B,C,D;
//定义一个形式参数并由main方法进行赋值
String name;
String S = "hello word";
public static void main(String[] args) {
BL x = new BL();
x.B =100;
x.C = -100;
x.D = 12200;
x.name = "this is name";
System.out.println(x.B);
System.out.println(x.C);
System.out.println(x.D);
System.out.println(x.S);
System.out.println(x.name);
System.out.println("-----------------------------------------------------");
Demo01 s = new Demo01();
s.names = "this is public";
     //通过方法给私有变量进行赋值
s.setA(100);
s.setS1("this is private");
s.names = "hello world";
     然后使用get到的值进行打印出值
System.out.println(s.getA() + s.getS1());
System.out.println(s.names);
}
}
#注:

private关键字
(1)私有的意义,可以修饰成员变量和成员方法

(2)特点:被private修饰的后的成员只能在本类中被访问

(3)private的应用:
以后再写一个类的时候:
把所有的成员变量给private了,提供对应的getXxx()/setXxx()方法
封装和private的应用:
A:把成员变量用private修饰 B:提高对应的getXxx()和setXxx()方法

1.变量的种类:
package com.run;

public class Employee {
static int allClicks=0; // 类变量
String str="hello world"; // 实例变量
public void method(){
int i =0; // 局部变量
}

}
  • 类变量:独立于方法之外的变量,用 static 修饰。
  • 实例变量:独立于方法之外的变量,不过没有 static 修饰。
  • 局部变量:类的方法中的变量。

 

示例:

package com.run;

public class Employee {
static int allClicks=0; // 类变量
String str="hello world"; // 实例变量
public void method(){
int i =0; // 局部变量
System.out.println(i);
}

public static void main(String[] args) {
Employee J = new Employee();
J.method();
String x = J.str;
System.out.println(x);
J.str = "java";
System.out.println(J.str);
allClicks = 1000;
System.out.println(allClicks);

}


打印结果:
0
hello world
java
1000
加入static修饰符后的变量可以直接在方法中使用

 

posted @ 2020-12-27 13:44  狸猫大侠  阅读(104)  评论(0编辑  收藏  举报