1.构造函数任何一个类不管它是抽象的还是具体的,都拥有一个构造函数,即使程序员不键入它,Java也会提供一个默认的无参的构造函数。构造函数必须要与 类同名,构造函数一定不能够有返回类型,切记void也是一种返回类型! 如果在类中没有创建任何构造函数,那么系统将使用默认的构造函数,如果程序员定义了一个构造函数,那么默认的构造函数将不存在! public class Book { private String id; private String title; private String author; //我们自己定义一个构造函数 public Book(String idIn,String titleIn,String authorIn){ id=idIn; title=titleIn; author=authorIn; } public String toString(){ return "The info of the book:\n"+ "Title:"+title+"\n"+ "Author:"+author+"\n"; }} public class Test { public static void main(String[]args){ //Book book=new Book(); 使用默认的构造函数将出现编译错误 Book book=new Book("0101001","Thinking in Java","Bruce Eckel"); System.out.println(book); }} 构造函数的执行方式: 首先调用其超类的构造函数,超类构造函数又调用其超类构造函数,直至到达Object构造函数为止,然后Object()构造函数执行,直到所 有的构造函数完成 public class Animal { public Animal(){ System.out.println("This is the animal constructor"); }}public class Snake extends Animal{ public Snake(){ System.out.println("This is snake constructor"); }}public class Cobra extends Snake{ public Cobra(){ System.out.println("This is the cobra constructor"); }}public class Test { public static void main(String[]args){ new Cobra(); }}执行结果:This is the animal constructorThis is snake constructorThis is the cobra constructor 默认构造函数是一个无变元的构造函数,隐式的包含了一个对super()的调用 如果一个子类的超类没有无参的构造函数,那么其子类必须程序员实现构造函数,而无法调用默认的构造函数 public class Rpg { private int hp; private int mp; private int grade; private int exp; public Rpg(int hpIn,int mpIn,int gradeIn,int expIn){ hp=hpIn; mp=mpIn; grade=gradeIn; exp=expIn; }}public class Magician extends Rpg{ //public Magician(){ 不可以使用默认的构造函数! //} public Magician(int hpIn,int mpIn,int gradeIn,int expIn){ super(hpIn,mpIn,gradeIn,expIn); }} 构造函数可以重载,如果在同一个类中一个构造函数需要调用另一个重载的构造函数,可以使用this(),this()的变元列表决定了调用哪个 具体的构造函数注意:this()和super()必须出现在构造函数的第一行!!!而且this()和super()函数不能位于同一个构造函数中!!! 抽象类的构造函数在实例化具体子类时被调用 接口是没有构造函数的! 2.初始化块:Java类中执行操作的地方有三个:构造函数、方法和初始化块 Java初始化块分为静态初始化块和实例初始化块: 首次加载类时,会运行一次静态初始化块,每次创建一个新实例时,都会运行一次实例初始化块,类中允许出现多个初始化块,它们所执行的顺序与它们 在代码中所出现的顺序相同 总体的执行顺序:静态初始化块->super()->实例初始化块->构造函数的其它部分,通过一个例子来说明: public class Father { public Father(){ System.out.println("This is super class!"); }}public class Test extends Father{ static{ System.out.println("This is static block!"); } public Test(){ System.out.println("This is test constructor"); } public static void main(String[]args){ System.out.println("Hello,Java!"); Test test=new Test(); } { System.out.println("Common init block!"); }}上面的例子的输出结果是:This is static block!Hello,Java!This is super class!Common init block!This is test constructor根据上面的规则,考虑一下为什么是这个结果.
Java之构造函数与初始化块
最新推荐文章于 2023-04-03 16:00:21 发布