package test; public class Testone { public static void main(String[] args) { Foo obj1 = new Foo(); } } class Foo { int value; public Foo(int initValue) { //自定义的构造方法(带参数) value=initValue; } }
编译出错:The constructor Foo() is undefined。原因:如果类提供了一个自定义的构造方法,将导致系统不再提供默认构造方法Foo()。
如何在静态方法中访问类的实例成员?
首先实例化一个对象,然后通过 对象名.成员 访问。
package test; public class TestTwo { public String name; public int age; public void information(){ } public static void main(String[] args) { TestTwo p1 =new TestTwo(); //实例化对象 p1.name="szj"; System.out.println(p1.name); } }
使用类的静态字段和构造函数,可以跟踪某个类所创建对象的个数。请写一个类,在任何时候都可以向它查询“你已经创建了多少个对象
1 package test; 2 3 public class SearchObjQ { 4 5 @SuppressWarnings("unused") 6 public static void main(String[] args) { 7 Creat a=new Creat(); 8 Creat b=new Creat(); 9 Creat c=new Creat(); 10 a.out(); 11 } 12 } 13 class Creat{ 14 static int n=0; 15 Creat(){ 16 n++; 17 } 18 public void out(){ 19 System.out.println("你已经创建了"+n+"个对象!"); 20 } 21 }
运行截图: