super会调用父类对象的应用,super()调用父类的方法;则是父类的构造啊只能出现在子类的方法或者构造方法中
在子类中使用构造方法的时候会先调用父类的构造方法,因为这里隐藏了一局super();
如果在子类中自己显示的定义了super();那必须要在第一行,否则就会报错
this();和super();不能一起用。
如果父类没有无参构造(父类写了有参构造且没有把无参构造显相的写出来)super();调用不来无参构造,而且子类无法无参构造
super只能在继承条件下才可以使用
this会调用当前类中的对象且一般都会使用this来调用当前类而不是不写,this()调用本类的方法
this无论有没有继承都可以使用
用this();调用自己的有参构造的时候也必须是第一行
package com.oo.oop.inherit; public class Life /*extends Object*/ { //public可以直接继承使用,而private私有的无法直接使用,依然需要get/set protected int time=10_0000_0000; public Life() { System.out.println("Life无参构造"); } public void print() { System.out.println("Life"); } }
package com.oo.oop.inherit; //子类继承父类就继承了父类的全部方法(前提是修饰符是public) public class Work extends Life{ private int time=1000_0000; public Work() { //隐藏代码:super();调用父类的无参构造 super();//调用父类的构造器,必须在子类的构造器的第一行 System.out.println("Work无参构造"); } public void second(int time){ System.out.println(time); System.out.println(this.time); System.out.println(super.time); } public void print() { System.out.println("Work"); } public void word(){ print(); this.print(); super.print(); } }
package com.oo; import com.oo.oop.inherit.Rest; import com.oo.oop.inherit.Work; // 一个项目应该只有一个main()方法 public class Application { public static void main(String[] args) { Work work = new Work(); //work.second(100000); //work.word(); } }