项目管理系统软件,seo工资服务,南京网站设计机构,网站整体运营2019独角兽企业重金招聘Python工程师标准 this与super关键字在java中构造函数中的应用#xff1a; ** super()函数 ** super()函数在子类构造函数中调用父类的构造函数时使用#xff0c;而且必须要在构造函数的第一行#xff0c;例如#xff1a; class Ani… 2019独角兽企业重金招聘Python工程师标准 this与super关键字在java中构造函数中的应用 ** super()函数 ** super()函数在子类构造函数中调用父类的构造函数时使用而且必须要在构造函数的第一行例如 class Animal {public Animal() {System.out.println(An Animal);}
}
class Dog extends Animal {public Dog() {super();System.out.println(A Dog);//super();错误的因为super()方法必须在构造函数的第一行//如果子类构造函数中没有写super()函数编译器会自动帮我们添加一个无参数的super()}
}
class Test{public static void main(String [] args){Dog dog new Dog();}
} 执行这段代码的结果为 An Animal A Dog 定义子类的一个对象时会先调用子类的构造函数然后在调用父类的构造函数如果父类函数足够多的话会一直调用到最终的父类构造函数函数调用时会使用栈空间所以按照入栈的顺序最先进入的是子类的构造函数然后才是邻近的父类构造函数最后再栈顶的是最终的父类构造函数构造函数执行是则按照从栈顶到栈底的顺序依次执行所以本例中的执行结果是先执行Animal的构造函数然后再执行子类的构造函数。 class Animal {private String name;public String getName(){name name;}public Animal(String name) {this.name name;}
}
class Dog extends Animal {public Dog() {super(name);}
}
class Test{public static void main(String [] args){Dog dog new Dog(jack);System.out.println(dog.getName());}
} 运行结果 jack 当父类构造函数有参数时如果要获取父类的private的成员变量并给其赋值作为子类的结果此时在定义子类的构造函数时就需要调用父类的构造函数并传值如上例所示。 this()函数 this()函数主要应用于同一类中从某个构造函数调用另一个重载版的构造函数。this()只能用在构造函数中并且也只能在第一行。所以在同一个构造函数中this()和super()不能同时出现。 例如下面的这个例子 class Mini extends Car {Color color;//无参数函数以默认的颜色调用真正的构造函数public Mini() {this(color.Red);}//真正的构造函数public Mini(Color c){super(mini);color c;}//不能同时调用super()和this(),因为他们只能选择一个public Mini(int size) {super(size);this(color.Red);
} 所以综上所述super()与this()的区别主要有以下 不同点 1、super()主要是对父类构造函数的调用this()是对重载构造函数的调用 2、super()主要是在继承了父类的子类的构造函数中使用是在不同类中的使用this()主要是在同一类的不同构造函数中的使用 相同点 1、super()和this()都必须在构造函数的第一行进行调用否则就是错误的 转载于:https://my.oschina.net/architectliuyuanyuan/blog/1615650