标签:
public class Test {
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;
public class Test {
public static void main(String[] args){
Foo obj1=new Foo();
}
}
class Foo{
int value;
public Foo(int initValue ){
value=initValue;
}
}
Foo obj1=new Foo();应该为 Foo obj1=new Foo(数);
public class Test {
public static void main(String[] args){
InitializeBlockClass obj=new InitializeBlockClass();
System.out.println(obj.field);//?
obj=new InitializeBlockClass(300);
System.out.println(obj.field);//?
}
}
class InitializeBlockClass{
{
field=200;
}
public int field=100;
public InitializeBlockClass(int value)
{
this.field=value;
}
public InitializeBlockClass() {
}
}
Java字段初始化的规律:
所有类的变量都默认初始化为null,比如String a; Integer b; 数字类的原始数据类型默认初始化为0,比如int a; short b; char c; boolean默认初始化为false
;
public class InitializeBlockDemo {
public static void main(String[] args) {
InitializeBlockClass obj=new InitializeBlockClass();
System.out.println(obj.field);
obj=new InitializeBlockClass(300);
System.out.println(obj.field);
}
}
class InitializeBlockClass{
//下面这句在初始化块之前与之后,会影响到field字段的初始值 //
public int field=100;
{
field=200;
}
public int field=100;
public InitializeBlockClass(int value)
{
this.field=value;
}
public InitializeBlockClass(){
}
}
public class Ex
{
int i =123; static int Temp;
public static void A()
{
System.out.println(Temp);
}
public int B()
{
int x = 100;
return x;
}
public static void main(String args[]) {
Ex e = new Ex();
Temp = e.B();
e.A();
}
}
使用类的静态字段和构造函数,我们可以跟踪某个类所创建对象的个数。请写一个类,在任何时候都可以向它查询“你已经创建了多少个对象?”:
public class Student{
public static void main(String[] args){
Information a = new Information();
a.OutputInformation();
Information b = new Information();
b.OutputInformation();
}
}
//定义类
class Information{
static int num=0;
Information()
{
num++;
}
public void OutputInformation()
{
System.out.println("你已经创建了"+num+"个对象!");
}
}
标签:
原文地址:http://www.cnblogs.com/liguoshuai/p/4888271.html