package test;
class Person {
private int age;
{ //构造代码块, 先于构造函数运行
System.out.println("person code run");
eat();
}
Person(int age) {
this.age = age;
System.out.println("age = " + age);
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
void eat() {
System.out.println("eat!!!");
}
}
public class Test {
public static void main(String[] args) {
Person a = new Person(12);
}
}
/*输出
person code run
eat!!!
age = 12
*/
Java面向对象 构造代码块
最新推荐文章于 2024-08-18 19:33:08 发布