1、
public class Text {
public static void main(String[] args) {
Foo obj1=new Foo();
Foo obj2=new Foo();
System.out.println(obj1==obj2);
}
}
class Foo{
int value=100;
}
运行结果:
false
2、
public class Text {
public static void main(String[] args) {
Foo obj1=new Foo();
}
}
class Foo{
int value;
public Foo(int IntiValue){
value=IntiValue;
}
}
出错:The constructor Foo() is undefined
3、
public class InitializeBlockClass{
{
field=200;
}
public int field=100;
public InitializeBlockClass(int value){
this.field=value;
}
public InitializeBlockClass(){
}
public static void main(String[]args) {
InitializeBlockClass obj=new InitializeBlockClass();
System.out.println(obj.field);//?
obj=new InitializeBlockClass(300);
System.out.println(obj.field);//?
}
}
输出结果:
100
300
Java字段初始化的规律:在new对象的时候就执行了。
4、
public class Test{
int x=1;
static int y=2;
public static void method(){//静态方法
System.out.println("实例变量x = " + new Test().x);//在静态方法中访问类的实例变量需首先进行类的实例化
System.out.println("静态变量y = " + y);//在静态方法中可直接访问类的静态变量
}
public static void main(String[] args) {
Test.method();
Test t = new Test();
System.out.println("x = " + t.x);
}
}
运行结果:
实例变量x = 1
静态变量y = 2
x = 1