能理解下面的代码,你也就差不多了。
class Person
{
private String name;
private int age=0;
private static String country="cn";
Person(String name,int age)
{
this.name=name;
this.age=age;
}
static
{
System.out.println("静态代码块被执行");
}
{ System.out.println(name+"..."+age);}
public void setName(String name)
{
this.name=name;
}
public void speak()
{
System.out.println(this.name+"..."+this.age);
}
public static void showCountry()
{
System.out.println("country="+country);
}
}
class StaticDemo
{
static
{
System.out.println("StaticDemo 静态代码块1");
}
public static void main(String[] args)
{
Person p=new Person("zhangsan",100);
p.setName("lisi");
p.speak();
Person.showCountry();
}
static
{
System.out.println("StaticDemo 静态代码块2");
}
}
输出结果:
StaticDemo 静态代码块1
StaticDemo 静态代码块2
静态代码块被执行
null...0 //构造代码块
lisi...100 //speak()
country=cn //showCountry() |
|