1 public class Main { 2 public static void main(String[] args) { 3 Foo obj1=new Foo(); 4 Foo obj2=new Foo(); 5 System.out.println(obj1==obj2); 6 } 7 static class Foo{ 8 Foo(){ 9 } 10 int value = 100; 11 } 12 }
打印结果为false,因为new出来的对象都是地址,==号比较的是地址值,两个的地址当然不一样
1 public class Main { 2 public static void main(String[] args) { 3 Foo obj1=new Foo(); 4 Foo obj2=new Foo(); 5 System.out.println(obj1==obj2); 6 } 7 static class Foo{ 8 int value; 9 public Foo(int a){ 10 11 value=a; 12 } 13 } 14 }
报错是因为,我们自己写的有参构造函数会将虚拟机自带的无参构造函数覆盖,导致主函数无法定义一个无参的对象
1 public class Main { 2 public static void main(String[] args) { 3 Foo obj=new Foo(); 4 System.out.println(obj.filed);//100 5 obj=new Foo(300); 6 System.out.println(obj.filed);//300 7 } 8 static class Foo{ 9 { 10 filed=200; 11 } 12 public int filed=100; 13 public Foo(int a){ 14 this.filed=a; 15 } 16 public Foo(){ 17 } 18 } 19 }
在进行赋初值的时候,会先调用与参数相匹配的构造函数,有参调用有参,无参调用无参
标签:9.27,int,动脑,class,static,new,Java,Foo,public From: https://www.cnblogs.com/Lyh3012648079/p/17734313.html