上代码:
package com.wjy;
public class Test {
public static void main(String[] args){
Student s1=new Student(99);
}
}
class Student{
public static Student stu=new Student(22); // 这里必须要static修饰,否则会出错。
public Student(int age){
System.out.println("The age is: "+age);
}
}
运行结果:
The age is: 22
The age is: 99
再看一个例子:
public class Test {
public static void main(String[] args) {
Activator activator = new Activator(23);
System.out.println("The age is " + activator.age);
}
}
class Activator {
private Activator plugin;
protected int age;
public Activator(int age) {
plugin = this;
this.age = age;
System.out.println("The age is " + age);
}
}
运行结果:
The age is 23
The age is 23
以上代码和下面的代码等价:
//*****************************************************************************
package com.wjy;
public class Test {
public static void main(String[] args) {
Activator activator = new Activator(23);
activator.showAge();
activator.getActivator().showAge();
}
}
class Activator {
private Activator plugin; //这里不需要用static修饰了。
protected int age;
public Activator(int age) {
this.age = age;
}
public Activator getActivator() {
plugin = this;
return plugin;
}
public void showAge() {
System.out.println("The age is " + age);
}
}
//****************************************************************************