类是公共的
有一个无参的公共的构造器
有属性 且有对应的get set方法
static
public class People {
private String name;
private int age;
// private String country;
private static String country;
//alt + insert 快捷键
public People() {
}
public People(String name, int age, String country) {
this.name = name;
this.setAge(age);
this.country = country;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
if (age>0 &&age<200){
this.age = age;
}
}
public void setCountry(String country) {
this.country = country;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getCountry() {
return country;
}
@Override
public String toString() {
return "People{" +
"name='" + name + '\'' +
", age=" + age +
", country='" + country + '\'' +
'}';
}
}
public class PeopleTest {
public static void main(String[] args) {
//new+对象/变量的类型+Ctrl+Alt+V自动生成变量名
//验证static关键字修饰的静态成员是否与创建对象无关
System.out.println(People.country);
//已经改为公共权限
People people1= new People();
people1.setAge(13);
people1.setCountry("china");
people1.setName("laa");
People people = new People("la",12,"china");
String s1 = people1.toString();
System.out.println(s1);
people1.setCountry("bianle");
s1 = people1.toString();
String s2 = people.toString();
System.out.println(s2);
System.out.println(s1);
//static 定义在Javabeen里 被其对象共享
People people2 = new People();
String s3 = people2.toString();
System.out.println(s3);
}
}
static用法:
1.修饰成员变量
2.修饰成员方法
public class StaticTest { //隶属于对象级 private int cnt =1; //设置复制上一行代码 ctrl+d //隶属于类层级 所有对象独享同一份 private static int snt =2; public void show(){ System.out.println(cnt); System.out.println(snt); } //自定义静态成员方法 推荐用类名.方法访问 //静态的方法 恒定的方法 不能打印可变的属性? //不是同一个层级 // 报错:java: 无法从静态上下文中引用非静态 变量 cnt //静态方法中只能访问静态变量 因为静态方法和静态变量是存在在方法区(可以理解为公共区域) // 而非静态变量是存放在栈(理解为私人区域) 不属于同一个区域 没办法直接调用 // 要访问非静态变量成员属性得通过new对象访问 public static void test(){ // System.out.println(cnt); System.out.println(snt); } public static void main(String[] args) { // StaticTest.show(); //Non-static method 'show()' cannot be referenced from a static context StaticTest staticTest = new StaticTest(); staticTest.show(); staticTest.test(); } }
静态方法中只能访问静态变量 因为静态方法和静态变量是存在在方法区(可以理解为公共区域)而非静态变量是存放在栈(理解为私人区域) 不属于同一个区域 没办法直接调用 要访问非静态变量成员属性得通过new对象访问 和类的加载顺序 普通变量的权限无关
在一个类里 一个静态方法无法调用非静态的变量 可以想象这种情况 当通过类名来调用这个静态方法(static修饰成为类层级)的时候 这个类的对象 可能还没有创建 同理这个变量也没有(是指连默认值都没有打那种 没有开辟存储空间
JVM好几个区
堆 最大 new的 静态变量的数据
栈 非静态变量
方法区 静态变量的引用 方法
构造块
构造块:在类体中直接使用{}括起来的代码块
每次创建对象都会执行一次构造块
public class Blocktest {
{//随着对象的创建而执行
System.out.println("构造块");
}
static {
System.out.println("静态代码块");
}
//自定义构造方法
public Blocktest(){
System.out.println("构造方法体");
}
public static void main(String[] args) {
Blocktest blocktest = new Blocktest();
Blocktest blocktest2 = new Blocktest();
}
}
当需要在执行构造方法体之前做一些准备工作时
eg:对成员变量进行统一初始化操作
静态代码块:
随着类的加载而执行
在执行代码块儿之前随着类的加载做一些准备工作
eg:加载数据库驱动包
随着类的加载vs随着对象的加载
执行顺序:
静态代码块>代码块>构造方法体