package com.Brooke01;
public class CodeBlockDemo1 {
public static void main(String[] args) {
{
int num = 10;
System.out.println(num);
}
}
}
package com.Brooke01;
public class CodeBlockDemo2 {
public static void main(String[] args) {
String name = "苍老师";
int age = 30;
Teacher ter1 = new Teacher();
Teacher ter2 = new Teacher(name,age);
}
}
class Teacher {
String name;
int age;
{
System.out.println("我爱Java!");
}
public Teacher() {
System.out.println("我是无参构造");
}
public Teacher(String name,int age) {
this.name = name;
this.age = age;
System.out.println("我是有参构造");
}
}
结果:
我爱Java!
我是无参构造
我爱Java!
我是有参构造
package com.Brooke01;
public class CodeBlockDemo3 {
public static void main(String[] args) {
String name = "苍老师";
int age = 30;
Teacher1 ter1 = new Teacher1();
Teacher1 ter2 = new Teacher1(name,age);
}
}
class Teacher1 {
String name;
int age;
static{
System.out.println("我爱Java!");
}
public Teacher1() {
System.out.println("我是无参构造");
}
public Teacher1(String name,int age) {
this.name = name;
this.age = age;
System.out.println("我是有参构造");
}
}
结果:
我爱Java!
我是无参构造
我是有参构造
package com.Brooke01;
public class CodeBlockDemo4 {
static {
System.out.println("CoderBlockDemo4的静态代码块执行");
}
{
System.out.println("CoderBlockDemo4的静态代码块执行");
}
public static void main(String[] args) {
System.out.println("CodeBlockDemo4主函数执行");
Coder c1 = new Coder();
Coder c2 = new Coder();
}
}
class Coder {
static {
System.out.println("Coder的静态代码块执行");
}
{
System.out.println("Coder的构造代码块执行");
}
public Coder() {
System.out.println("Coder的无参构造执行");
}
}
结果:
CoderBlockDemo4的静态代码块执行
CodeBlockDemo4主函数执行
Coder的静态代码块执行
Coder的构造代码块执行
Coder的无参构造执行
Coder的构造代码块执行
Coder的无参构造执行