public class HelloWorld {
private String name; // 声明变量name
private String sex; // 声明变量sex
static int age;// 声明静态变量age
// 构造方法
public HelloWorld () {
System.out.println("通过构造方法初始化name");
name = "tom";
}
// 初始化块
{
System.out.println("通过初始化块初始化sex");
sex = "男";
}
// 静态初始化块
static {
System.out.println("通过静态初始化块初始化age");
age = 20;
}
public void show() {
System.out.println("姓名:" + name + ",性别:" + sex + ",年龄:" + age);
}
public static void main(String[] args) {
// 创建对象
HelloWorld hello = new HelloWorld();
// 调用对象的show方法
hello.show();
}
}
下面是封装的数据:
package fengzhuang; public class fengzhuang { private String name; private String sex; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } @Override public String toString() { return " 姓名:" + name + ", 性别:" + sex ; }
,接下来在另外一个类中调用:
package fengzhuang; public class test01 { static int age; fengzhuang test=new fengzhuang(); //构造方法 public test01 () { System.out.println("通过构造方法初始化name"); //test.setName(name);name = "tom"; test.setName("tom"); } // 初始化块 { System.out.println("通过初始化块初始化sex"); //sex = "男"; test.setSex("男"); } // 静态初始化块 static { System.out.println("通过静态初始化块初始化age"); age = 20; } public void show() { //System.out.println("姓名:" + name + ",性别:" + sex + ",年龄:" + age); System.out.println(test.toString()+",年龄:"+age); } public static void main(String[] args) { test01 Test = new test01(); Test.show(); } }
静态变量不用封装,因为它是共享的!(完)
好棒!